Skip to content

Commit

Permalink
Return on abort
Browse files Browse the repository at this point in the history
Signed-off-by: Marcos Candeia <[email protected]>
  • Loading branch information
mcandeia committed Oct 18, 2024
1 parent ed66f4f commit 897d65a
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/actors/util/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export class WatchTarget<T> {
private subscribers: Record<string, (value: T) => void> = {};

// Subscribe to changes and get an async iterator
subscribe(): AsyncIterableIterator<T> {
subscribe(signal?: AbortSignal): AsyncIterableIterator<T> {
const subscriptionId = crypto.randomUUID();
const queue: Array<(value: IteratorResult<T>) => void> = [];

Expand All @@ -16,7 +16,12 @@ export class WatchTarget<T> {

const nextPromise = () =>
new Promise<IteratorResult<T>>((resolve) => {
queue.push(resolve);
queue.push((v) => {
if (signal?.aborted) {
return resolve({ value: undefined, done: true });
}
resolve(v);
});
});

const iterator: AsyncIterableIterator<T> = {
Expand All @@ -34,6 +39,9 @@ export class WatchTarget<T> {
this.subscribers[subscriptionId] = (value: T) => {
pushQueue({ value, done: false });
};
signal?.addEventListener("abort", () => {
iterator?.return?.();
});

return iterator;
}
Expand Down

0 comments on commit 897d65a

Please sign in to comment.