Skip to content

Commit

Permalink
remove event listener on counter updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Francesco Rivola committed Feb 12, 2024
1 parent 2009a83 commit c153f64
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
12 changes: 7 additions & 5 deletions src/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ type Counter = {
incrementCounter: () => void;
decrementCounter: () => void;
getCount: () => number;
registerSubscriberToCounterChanges(callback: (count: number) => void): void;
addCounterUpdateEventListener(callback: (count: number) => void): void;
removeCounterUpdateEventListener(callback: (count: number) => void): void;
};

export function createCounter(): Counter {
Expand All @@ -23,10 +24,11 @@ export function createCounter(): Counter {
getCount(): number {
return count;
},
registerSubscriberToCounterChanges(
callback: (count: number) => void,
): void {
eventEmitter.on("counterUpdate", callback);
addCounterUpdateEventListener(callback: (count: number) => void): void {
eventEmitter.addListener("counterUpdate", callback);
},
removeCounterUpdateEventListener(callback: (count: number) => void): void {
eventEmitter.removeListener("counterUpdate", callback);
},
};
}
21 changes: 11 additions & 10 deletions src/fire-and-forgetter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,22 +105,23 @@ export function fireAndForgetter(options?: Options): FireAndForgetter {
resolve();
return;
}
counter.registerSubscriberToCounterChanges((count) => {
function onCounterUpdate(count) {
if (count === 0) {
counter.removeCounterUpdateEventListener(onCounterUpdate);
resolve();
}
});
}
counter.addCounterUpdateEventListener(onCounterUpdate);
const { timeout } = closeOptions;
if (timeout > 0) {
setTimeout(
() =>
reject(
new TimeoutClosingError(
`Cannot close after ${timeout}ms, ${counter.getCount()} fire and forget operations are still in progress`,
),
setTimeout(() => {
counter.removeCounterUpdateEventListener(onCounterUpdate);
reject(
new TimeoutClosingError(
`Cannot close after ${timeout}ms, ${counter.getCount()} fire and forget operations are still in progress`,
),
timeout,
);
);
}, timeout);
}
});
}
Expand Down

0 comments on commit c153f64

Please sign in to comment.