Open History to see the last commit
1import { scheduleMicrotask } from './utils'
2β
3// TYPES
4β
5type NotifyCallback = () => void
6β
7type NotifyFunction = (callback: () => void) => void
8β
9type BatchNotifyFunction = (callback: () => void) => void
10β
11// CLASS
12β
13class NotifyManager {
14 private queue: NotifyCallback[]
15 private transactions: number
16 private notifyFn: NotifyFunction
17 private batchNotifyFn: BatchNotifyFunction
18β
19 constructor() {
20 this.queue = []
21 this.transactions = 0
22β
23 this.notifyFn = (callback: () => void) => {
24 callback()
25 }
26β
27 this.batchNotifyFn = (callback: () => void) => {
28 callback()
29 }
30 }
31β
32 batch<T>(callback: () => T): T {
33 this.transactions++
34 const result = callback()
35 this.transactions--
36 if (!this.transactions) {
37 this.flush()
38 }
39 return result
40 }
41β
42 schedule(callback: NotifyCallback): void {
43 if (this.transactions) {
44 this.queue.push(callback)
45 } else {
46 scheduleMicrotask(() => {
47 this.notifyFn(callback)
48 })
49 }
50 }
51β
52 /**
53 * All calls to the wrapped function will be batched.
54 */
55 batchCalls<T extends Function>(callback: T): T {
56 return ((...args: any[]) => {
57 this.schedule(() => {
58 callback(...args)
59 })
60 }) as any
61 }
62β
63 flush(): void {
64 const queue = this.queue
65 this.queue = []
66 if (queue.length) {
67 scheduleMicrotask(() => {
68 this.batchNotifyFn(() => {
69 queue.forEach(callback => {
70 this.notifyFn(callback)
71 })
72 })
73 })
74 }
75 }
76β
77 /**
78 * Use this method to set a custom notify function.
79 * This can be used to for example wrap notifications with `React.act` while running tests.
80 */
81 setNotifyFunction(fn: NotifyFunction) {
82 this.notifyFn = fn
83 }
84β
85 /**
86 * Use this method to set a custom function to batch notifications together into a single tick.
87 * By default React Query will use the batch function provided by ReactDOM or React Native.
88 */
89 setBatchNotifyFunction(fn: BatchNotifyFunction) {
90 this.batchNotifyFn = fn
91 }
92}
93β
94// SINGLETON
95β
96export const notifyManager = new NotifyManager()