Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
eb1e201
commit 4026b95
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { AsyncChangeListener, UnsubscribeFn } from "./types"; | ||
|
||
export class NotifierAsync<T> extends Set<AsyncChangeListener<T>> { | ||
subscribe(listener: AsyncChangeListener<T>): UnsubscribeFn { | ||
this.add(listener); | ||
|
||
return () => this.unsubscribe(listener); | ||
} | ||
|
||
unsubscribe(listener: AsyncChangeListener<T>) { | ||
this.delete(listener); | ||
} | ||
|
||
notify(value: T): void | Promise<void>; | ||
notify(value: T, ...otherArgs: any[]): void | Promise<void>; | ||
notify(...args: any[]): void | Promise<void> { | ||
const promises: Promise<void>[] = []; | ||
Array.from(this.values()).forEach((listener) => { | ||
const promiseOrVoid = listener(...(args as [T])); | ||
if (isPromise(promiseOrVoid)) { | ||
promises.push(promiseOrVoid); | ||
} | ||
}); | ||
if (promises.length) { | ||
return Promise.all(promises).then(() => {}); | ||
} | ||
} | ||
|
||
static get<T>(abon: any): NotifierAsync<T> { | ||
return (abon as any)[KEY]; | ||
} | ||
|
||
static define<T>(abon: T): T { | ||
Object.defineProperty(abon, KEY, { | ||
value: new NotifierAsync(), | ||
configurable: false, | ||
writable: false, | ||
enumerable: false, | ||
}); | ||
|
||
return abon; | ||
} | ||
} | ||
|
||
const KEY = "__notifier"; | ||
|
||
function isPromise(v: any): v is Promise<any> { | ||
return Boolean(v && typeof v["then"] === "function"); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters