-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathemitter.ts
61 lines (51 loc) · 1.26 KB
/
emitter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { logger } from "@coder/logger"
/**
* Event emitter callback. Called with the emitted value and a promise that
* resolves when all emitters have finished.
*/
export type Callback<T, R = void | Promise<void>> = (t: T, p: Promise<void>) => R
export interface Disposable {
dispose(): void | Promise<void>
}
export interface Event<T> {
(listener: Callback<T>): Disposable
}
/**
* Emitter typecasts for a single event type.
*/
export class Emitter<T> {
private listeners: Array<Callback<T>> = []
public get event(): Event<T> {
return (cb: Callback<T>): Disposable => {
this.listeners.push(cb)
return {
dispose: (): void => {
const i = this.listeners.indexOf(cb)
if (i !== -1) {
this.listeners.splice(i, 1)
}
},
}
}
}
/**
* Emit an event with a value.
*/
public async emit(value: T): Promise<void> {
let resolve: () => void
const promise = new Promise<void>((r) => (resolve = r))
await Promise.all(
this.listeners.map(async (cb) => {
try {
await cb(value, promise)
} catch (error: any) {
logger.error(error.message)
}
}),
)
resolve!()
}
public dispose(): void {
this.listeners = []
}
}