forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotifyManager.ts
56 lines (46 loc) · 1 KB
/
notifyManager.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
import { getBatchedUpdates, scheduleMicrotask } from './utils'
// TYPES
type NotifyCallback = () => void
// CLASS
export class NotifyManager {
private queue: NotifyCallback[]
private transactions: number
constructor() {
this.queue = []
this.transactions = 0
}
batch<T>(callback: () => T): T {
this.transactions++
const result = callback()
this.transactions--
if (!this.transactions) {
this.flush()
}
return result
}
schedule(notify: NotifyCallback): void {
if (this.transactions) {
this.queue.push(notify)
} else {
scheduleMicrotask(() => {
notify()
})
}
}
flush(): void {
const queue = this.queue
this.queue = []
if (queue.length) {
scheduleMicrotask(() => {
const batchedUpdates = getBatchedUpdates()
batchedUpdates(() => {
queue.forEach(notify => {
notify()
})
})
})
}
}
}
// SINGLETON
export const notifyManager = new NotifyManager()