Open History to see the last commit
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β
15/**
16 * Default scheduling function used by the notify manager. Schedules the
17 * callback with the system's `setTimeout(callback, 0)`.
18 */
19export const defaultScheduler: ScheduleFunction = systemSetTimeoutZero
20β
21/**
22 * Creates a notify manager, which schedules and batches notifications to
23 * subscribers. Query uses a single instance of it, exported as
24 * {@link notifyManager}.
25 *
26 * @returns A new notify manager.
27 */
28export function createNotifyManager() {
29 let queue: Array<NotifyCallback> = []
30 let transactions = 0
31 let notifyFn: NotifyFunction = (callback) => {
32 callback()
33 }
34 let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {
35 callback()
36 }
37 let scheduleFn = defaultScheduler
38β
39 const schedule = (callback: NotifyCallback): void => {
40 if (transactions) {
41 queue.push(callback)
42 } else {
43 scheduleFn(() => {
44 notifyFn(callback)
45 })
46 }
47 }
48 const flush = (): void => {
49 const originalQueue = queue
50 queue = []
51 if (originalQueue.length) {
52 scheduleFn(() => {
53 batchNotifyFn(() => {
54 originalQueue.forEach((callback) => {
55 notifyFn(callback)
56 })
57 })
58 })
59 }
60 }
61β
62 return {
63 /**
64 * Batches all updates scheduled inside the passed callback. This is mainly
65 * used internally to optimize query client updating. Batches can be nested;
66 * the queue is only flushed once the outermost `batch` call finishes. The
67 * return value of `callback` is passed through.
68 *
69 * @param callback - The function to run in the batch.
70 * @returns The return value of `callback`.
71 */
72 batch: <T>(callback: () => T): T => {
73 let result
74 transactions++
75 try {
76 result = callback()
77 } finally {
78 transactions--
79 if (!transactions) {
80 flush()
81 }
82 }
83 return result
84 },
85 /**
86 * All calls to the wrapped function will be batched.
87 *
88 * @param callback - The function to wrap.
89 * @returns A function that schedules a call to `callback` with the given
90 * arguments.
91 */
92 batchCalls: <T extends Array<unknown>>(
93 callback: BatchCallsCallback<T>,
94 ): BatchCallsCallback<T> => {
95 return (...args) => {
96 schedule(() => {
97 callback(...args)
98 })
99 }
100 },
101 /**
102 * Schedules a function to be run on the next batch. By default, the batch
103 * is run with a `setTimeout`, but this can be configured via
104 * `setScheduler`.
105 */
106 schedule,
107 /**
108 * Use this method to set a custom notify function. This can be used to for
109 * example wrap notifications with `React.act` while running tests.
110 *
111 * @param fn - Receives each notification callback and must call it.
112 */
113 setNotifyFunction: (fn: NotifyFunction) => {
114 notifyFn = fn
115 },
116 /**
117 * Use this method to set a custom function to batch notifications together
118 * into a single tick. Framework adapters use this to plug in their own
119 * batching primitive, so that a single query update only triggers one
120 * re-render instead of one per subscriber.
121 *
122 * @example
123 * ;```ts
124 * import { notifyManager } from '@tanstack/query-core'
125 * import { batch } from 'solid-js'
126 *
127 * notifyManager.setBatchNotifyFunction(batch)
128 * ```
129 *
130 * @param fn - Receives a function that runs a batch of notifications and
131 * must call it.
132 */
133 setBatchNotifyFunction: (fn: BatchNotifyFunction) => {
134 batchNotifyFn = fn
135 },
136 /**
137 * Configures a custom callback that schedules when the next batch runs. The
138 * default behavior is `setTimeout(callback, 0)`.
139 *
140 * @example
141 * ;```ts
142 * import { notifyManager } from '@tanstack/query-core'
143 *
144 * // Schedule batches in the next microtask
145 * notifyManager.setScheduler(queueMicrotask)
146 *
147 * // Schedule batches before the next frame is rendered
148 * notifyManager.setScheduler(requestAnimationFrame)
149 *
150 * // Schedule batches some time in the future
151 * notifyManager.setScheduler((cb) => setTimeout(cb, 10))
152 * ```
153 *
154 * @param fn - Receives a callback that runs the next batch, and schedules
155 * it.
156 */
157 setScheduler: (fn: ScheduleFunction) => {
158 scheduleFn = fn
159 },
160 } as const
161}
162β
163// SINGLETON
164β
165/** Handles scheduling and batching callbacks in TanStack Query. */
166export const notifyManager = createNotifyManager()