Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

notifyManager.ts

106 lines2.4 KB

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
104​
105// SINGLETON
106export const notifyManager = createNotifyManager()