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