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