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

notifyManager.ts

100 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​
11// CLASS
12​
13export class 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 let result
34 this.transactions++
35 try {
36 result = callback()
37 } finally {
38 this.transactions--
39 if (!this.transactions) {
40 this.flush()
41 }
42 }
43 return result
44 }
45​
46 schedule(callback: NotifyCallback): void {
47 if (this.transactions) {
48 this.queue.push(callback)
49 } else {
50 scheduleMicrotask(() => {
51 this.notifyFn(callback)
52 })
53 }
54 }
55​
56 /**
57 * All calls to the wrapped function will be batched.
58 */
59 batchCalls<T extends Function>(callback: T): T {
60 return ((...args: any[]) => {
61 this.schedule(() => {
62 callback(...args)
63 })
64 }) as any
65 }
66​
67 flush(): void {
68 const queue = this.queue
69 this.queue = []
70 if (queue.length) {
71 scheduleMicrotask(() => {
72 this.batchNotifyFn(() => {
73 queue.forEach(callback => {
74 this.notifyFn(callback)
75 })
76 })
77 })
78 }
79 }
80​
81 /**
82 * Use this method to set a custom notify function.
83 * This can be used to for example wrap notifications with `React.act` while running tests.
84 */
85 setNotifyFunction(fn: NotifyFunction) {
86 this.notifyFn = fn
87 }
88​
89 /**
90 * Use this method to set a custom function to batch notifications together into a single tick.
91 * By default React Query will use the batch function provided by ReactDOM or React Native.
92 */
93 setBatchNotifyFunction(fn: BatchNotifyFunction) {
94 this.batchNotifyFn = fn
95 }
97​
98// SINGLETON
99​
100export const notifyManager = new NotifyManager()