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

notifyManager.ts

100 lines2.2 KB

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