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

notifyManager.ts

99 lines2.4 KB

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