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