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

queriesObserver.ts

297 lines7.9 KB

1import { notifyManager } from './notifyManager'
2import { QueryObserver } from './queryObserver'
3import { Subscribable } from './subscribable'
4import { replaceEqualDeep } from './utils'
5import type {
6 DefaultedQueryObserverOptions,
7 QueryObserverOptions,
8 QueryObserverResult,
9} from './types'
10import type { QueryClient } from './queryClient'
11import type { NotifyOptions } from './queryObserver'
12​
13function difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {
14 return array1.filter((x) => !array2.includes(x))
16​
17function replaceAt<T>(array: Array<T>, index: number, value: T): Array<T> {
18 const copy = array.slice(0)
19 copy[index] = value
20 return copy
22​
23type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
24​
25type CombineFn<TCombinedResult> = (
26 result: Array<QueryObserverResult>,
27) => TCombinedResult
28​
29export interface QueriesObserverOptions<
30 TCombinedResult = Array<QueryObserverResult>,
31> {
32 combine?: CombineFn<TCombinedResult>
34​
35export class QueriesObserver<
36 TCombinedResult = Array<QueryObserverResult>,
37> extends Subscribable<QueriesObserverListener> {
38 #client: QueryClient
39 #result!: Array<QueryObserverResult>
40 #queries: Array<QueryObserverOptions>
41 #options?: QueriesObserverOptions<TCombinedResult>
42 #observers: Array<QueryObserver>
43 #combinedResult?: TCombinedResult
44 #lastCombine?: CombineFn<TCombinedResult>
45 #lastResult?: Array<QueryObserverResult>
46​
47 constructor(
48 client: QueryClient,
49 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
50 options?: QueriesObserverOptions<TCombinedResult>,
51 ) {
52 super()
53​
54 this.#client = client
55 this.#options = options
56 this.#queries = []
57 this.#observers = []
58 this.#result = []
59​
60 this.setQueries(queries)
61 }
62​
63 protected onSubscribe(): void {
64 if (this.listeners.size === 1) {
65 this.#observers.forEach((observer) => {
66 observer.subscribe((result) => {
67 this.#onUpdate(observer, result)
68 })
69 })
70 }
71 }
72​
73 protected onUnsubscribe(): void {
74 if (!this.listeners.size) {
75 this.destroy()
76 }
77 }
78​
79 destroy(): void {
80 this.listeners = new Set()
81 this.#observers.forEach((observer) => {
82 observer.destroy()
83 })
84 }
85​
86 setQueries(
87 queries: Array<QueryObserverOptions>,
88 options?: QueriesObserverOptions<TCombinedResult>,
89 notifyOptions?: NotifyOptions,
90 ): void {
91 this.#queries = queries
92 this.#options = options
93​
94 if (process.env.NODE_ENV !== 'production') {
95 const queryHashes = queries.map((query) => query.queryHash)
96 if (new Set(queryHashes).size !== queryHashes.length) {
97 console.warn(
98 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
99 )
100 }
101 }
102​
103 notifyManager.batch(() => {
104 const prevObservers = this.#observers
105​
106 const newObserverMatches = this.#findMatchingObservers(this.#queries)
107​
108 // set options for the new observers to notify of changes
109 newObserverMatches.forEach((match) =>
110 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
111 )
112​
113 const newObservers = newObserverMatches.map((match) => match.observer)
114 const newResult = newObservers.map((observer) =>
115 observer.getCurrentResult(),
116 )
117​
118 const hasIndexChange = newObservers.some(
119 (observer, index) => observer !== prevObservers[index],
120 )
121​
122 if (prevObservers.length === newObservers.length && !hasIndexChange) {
123 return
124 }
125​
126 this.#observers = newObservers
127 this.#result = newResult
128​
129 if (!this.hasListeners()) {
130 return
131 }
132​
133 difference(prevObservers, newObservers).forEach((observer) => {
134 observer.destroy()
135 })
136​
137 difference(newObservers, prevObservers).forEach((observer) => {
138 observer.subscribe((result) => {
139 this.#onUpdate(observer, result)
140 })
141 })
142​
143 this.#notify()
144 })
145 }
146​
147 getCurrentResult(): Array<QueryObserverResult> {
148 return this.#result
149 }
150​
151 getQueries() {
152 return this.#observers.map((observer) => observer.getCurrentQuery())
153 }
154​
155 getObservers() {
156 return this.#observers
157 }
158​
159 getOptimisticResult(
160 queries: Array<QueryObserverOptions>,
161 combine: CombineFn<TCombinedResult> | undefined,
162 ): [
163 rawResult: Array<QueryObserverResult>,
164 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
165 trackResult: () => Array<QueryObserverResult>,
166 ] {
167 const matches = this.#findMatchingObservers(queries)
168 const result = matches.map((match) =>
169 match.observer.getOptimisticResult(match.defaultedQueryOptions),
170 )
171​
172 return [
173 result,
174 (r?: Array<QueryObserverResult>) => {
175 return this.#combineResult(r ?? result, combine)
176 },
177 () => {
178 return this.#trackResult(result, queries)
179 },
180 ]
181 }
182​
183 #trackResult(
184 result: Array<QueryObserverResult>,
185 queries: Array<QueryObserverOptions>,
186 ) {
187 const matches = this.#findMatchingObservers(queries)
188​
189 return matches.map((match, index) => {
190 const observerResult = result[index]!
191 return !match.defaultedQueryOptions.notifyOnChangeProps
192 ? match.observer.trackResult(observerResult, (accessedProp) => {
193 // track property on all observers to ensure proper (synchronized) tracking (#7000)
194 matches.forEach((m) => {
195 m.observer.trackProp(accessedProp)
196 })
197 })
198 : observerResult
199 })
200 }
201​
202 #combineResult(
203 input: Array<QueryObserverResult>,
204 combine: CombineFn<TCombinedResult> | undefined,
205 ): TCombinedResult {
206 if (combine) {
207 if (
208 !this.#combinedResult ||
209 this.#result !== this.#lastResult ||
210 combine !== this.#lastCombine
211 ) {
212 this.#lastCombine = combine
213 this.#lastResult = this.#result
214 this.#combinedResult = replaceEqualDeep(
215 this.#combinedResult,
216 combine(input),
217 )
218 }
219​
220 return this.#combinedResult
221 }
222 return input as any
223 }
224​
225 #findMatchingObservers(
226 queries: Array<QueryObserverOptions>,
227 ): Array<QueryObserverMatch> {
228 const prevObserversMap = new Map(
229 this.#observers.map((observer) => [observer.options.queryHash, observer]),
230 )
231​
232 const observers: Array<QueryObserverMatch> = []
233​
234 queries.forEach((options) => {
235 const defaultedOptions = this.#client.defaultQueryOptions(options)
236 const match = prevObserversMap.get(defaultedOptions.queryHash)
237 if (match) {
238 observers.push({
239 defaultedQueryOptions: defaultedOptions,
240 observer: match,
241 })
242 } else {
243 const existingObserver = this.#observers.find(
244 (o) => o.options.queryHash === defaultedOptions.queryHash,
245 )
246 observers.push({
247 defaultedQueryOptions: defaultedOptions,
248 observer:
249 existingObserver ??
250 new QueryObserver(this.#client, defaultedOptions),
251 })
252 }
253 })
254​
255 return observers.sort((a, b) => {
256 return (
257 queries.findIndex(
258 (q) => q.queryHash === a.defaultedQueryOptions.queryHash,
259 ) -
260 queries.findIndex(
261 (q) => q.queryHash === b.defaultedQueryOptions.queryHash,
262 )
263 )
264 })
265 }
266​
267 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
268 const index = this.#observers.indexOf(observer)
269 if (index !== -1) {
270 this.#result = replaceAt(this.#result, index, result)
271 this.#notify()
272 }
273 }
274​
275 #notify(): void {
276 if (this.hasListeners()) {
277 const previousResult = this.#combinedResult
278 const newResult = this.#combineResult(
279 this.#trackResult(this.#result, this.#queries),
280 this.#options?.combine,
281 )
282​
283 if (previousResult !== newResult) {
284 notifyManager.batch(() => {
285 this.listeners.forEach((listener) => {
286 listener(this.#result)
287 })
288 })
289 }
290 }
291 }
293​
294type QueryObserverMatch = {
295 defaultedQueryOptions: DefaultedQueryObserverOptions
296 observer: QueryObserver