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