Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions __tests__/eventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,33 @@ describe("eventEmitter", () => {
expect(logUserLogin2).toHaveBeenCalled();
});

it("handles unsubscription of one listener by another during emission", () => {
const logUserLogin1 = jest.fn();
const logUserLogin2 = jest.fn();

// eslint-disable-next-line prefer-const
let unsubscribeSecond!: ReturnType<typeof subscribe>;

subscribe("userLogin", (eventName, data) => {
logUserLogin1(eventName, data);
unsubscribeSecond();
});

unsubscribeSecond = subscribe("userLogin", logUserLogin2);

// First emission: both listeners should be called once
emit("userLogin", { userId: "user1", timestamp: new Date() });

expect(logUserLogin1).toHaveBeenCalledTimes(1);
expect(logUserLogin2).toHaveBeenCalledTimes(1);

// Second emission: only the first listener should fire
emit("userLogin", { userId: "user1", timestamp: new Date() });

expect(logUserLogin1).toHaveBeenCalledTimes(2);
expect(logUserLogin2).toHaveBeenCalledTimes(1);
});

it("should not throw if emit is called without any listeners", () => {
expect(() => {
emit("userLogin", { userId: "user1", timestamp: new Date() });
Expand Down
7 changes: 4 additions & 3 deletions src/eventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,12 +478,13 @@ export const createEventEmitter = <
if (!listenersMapEntry) {
return;
}
listenersMapEntry.listeners.forEach(({ listener, predicate }) => {
const listeners = [...listenersMapEntry.listeners.values()];
for (const { listener, predicate } of listeners) {
if (predicate && !predicate(data)) {
return;
continue;
}
listener(eventName, data);
});
}
};

// Unsubscribe all listeners for a specific event or all events
Expand Down