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

notifyManager.ts

96 lines2.1 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​
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
94​
95// SINGLETON
96export const notifyManager = createNotifyManager()