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

notifyManager.ts

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