-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
broadcast.ts
67 lines (58 loc) 路 1.59 KB
/
broadcast.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
62
63
64
65
66
67
import { isFn } from '@uform/types'
import { each } from './array'
type Subscriber<N> = (notification: N) => void
type Filter<P, S> = (payload: P, subscription: S) => any
const noop = () => undefined
export interface IBroadcast extends Broadcast<any, any, any> {}
export class Broadcast<P, S, N> {
private entries = []
private buffer = []
private length: number
public subscribe(subscriber: Subscriber<N>, subscription?: any) {
if (!isFn(subscriber)) {
return noop
}
const index = this.entries.length
this.entries.push({
subscriber,
subscription
})
this.flushBuffer(this.entries[index])
return () => {
this.entries.splice(index, 1)
}
}
public unsubscribe() {
this.entries.length = 0
this.buffer.length = 0
}
public flushBuffer({ subscriber, subscription }) {
each(this.buffer, ({ payload, filter }) => {
if (isFn(filter)) {
const notification = filter(payload, subscription)
if (notification !== undefined) {
subscriber(notification)
}
} else {
subscriber(payload, subscription)
}
})
}
public notify(payload: P, filter?: Filter<P, S>) {
if (this.length === 0) {
this.buffer.push({ payload, filter })
return
}
each(this.entries, ({ subscriber, subscription }) => {
if (isFn(filter)) {
const notification = filter(payload, subscription)
if (notification !== undefined) {
subscriber(notification)
}
} else {
subscriber(payload, subscription)
}
})
this.buffer.length = 0
}
}