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 schedule = (callback: NotifyCallback): void => {
25 if (transactions) {
26 queue.push(callback)
27 } else {
28 scheduleFn(() => {
29 notifyFn(callback)
30 })
31 }
32 }
33 const flush = (): void => {
34 const originalQueue = queue
35 queue = []
36 if (originalQueue.length) {
37 scheduleFn(() => {
38 batchNotifyFn(() => {
39 originalQueue.forEach((callback) => {
40 notifyFn(callback)
41 })
42 })
43 })
44 }
45 }
46β
47 return {
48 batch: <T>(callback: () => T): T => {
49 let result
50 transactions++
51 try {
52 result = callback()
53 } finally {
54 transactions--
55 if (!transactions) {
56 flush()
57 }
58 }
59 return result
60 },
61 /**
62 * All calls to the wrapped function will be batched.
63 */
64 batchCalls: <T extends Array<unknown>>(
65 callback: BatchCallsCallback<T>,
66 ): BatchCallsCallback<T> => {
67 return (...args) => {
68 schedule(() => {
69 callback(...args)
70 })
71 }
72 },
73 schedule,
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 setNotifyFunction: (fn: NotifyFunction) => {
79 notifyFn = fn
80 },
81 /**
82 * Use this method to set a custom function to batch notifications together into a single tick.
83 * By default React Query will use the batch function provided by ReactDOM or React Native.
84 */
85 setBatchNotifyFunction: (fn: BatchNotifyFunction) => {
86 batchNotifyFn = fn
87 },
88 setScheduler: (fn: ScheduleFunction) => {
89 scheduleFn = fn
90 },
91 } as const
92}
93β
94// SINGLETON
95export const notifyManager = createNotifyManager()