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

notifyManager.ts

96 lines2.0 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​
11// CLASS
12​
13class NotifyManager {
14 private queue: NotifyCallback[]
15 private transactions: number
16 private notifyFn: NotifyFunction
17 private batchNotifyFn: BatchNotifyFunction
18​
19 constructor() {
20 this.queue = []
21 this.transactions = 0
22​
23 this.notifyFn = (callback: () => void) => {
24 callback()
25 }
26​
27 this.batchNotifyFn = (callback: () => void) => {
28 callback()
29 }
30 }
31​
32 batch<T>(callback: () => T): T {
33 this.transactions++
34 const result = callback()
35 this.transactions--
36 if (!this.transactions) {
37 this.flush()
38 }
39 return result
40 }
41​
42 schedule(callback: NotifyCallback): void {
43 if (this.transactions) {
44 this.queue.push(callback)
45 } else {
46 scheduleMicrotask(() => {
47 this.notifyFn(callback)
48 })
49 }
50 }
51​
52 /**
53 * All calls to the wrapped function will be batched.
54 */
55 batchCalls<T extends Function>(callback: T): T {
56 return ((...args: any[]) => {
57 this.schedule(() => {
58 callback(...args)
59 })
60 }) as any
61 }
62​
63 flush(): void {
64 const queue = this.queue
65 this.queue = []
66 if (queue.length) {
67 scheduleMicrotask(() => {
68 this.batchNotifyFn(() => {
69 queue.forEach(callback => {
70 this.notifyFn(callback)
71 })
72 })
73 })
74 }
75 }
76​
77 /**
78 * Use this method to set a custom notify function.
79 * This can be used to for example wrap notifications with `React.act` while running tests.
80 */
81 setNotifyFunction(fn: NotifyFunction) {
82 this.notifyFn = fn
83 }
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 this.batchNotifyFn = fn
91 }
93​
94// SINGLETON
95​
96export const notifyManager = new NotifyManager()