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

queriesObserver.ts

282 lines7.7 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 #observers: Array<QueryObserver>
42 #combinedResult?: TCombinedResult
43 #lastCombine?: CombineFn<TCombinedResult>
44 #lastResult?: Array<QueryObserverResult>
45​
46 constructor(
47 client: QueryClient,
48 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
49 _options?: QueriesObserverOptions<TCombinedResult>,
50 ) {
51 super()
52​
53 this.#client = client
54 this.#queries = []
55 this.#observers = []
56 this.#result = []
57​
58 this.setQueries(queries)
59 }
60​
61 protected onSubscribe(): void {
62 if (this.listeners.size === 1) {
63 this.#observers.forEach((observer) => {
64 observer.subscribe((result) => {
65 this.#onUpdate(observer, result)
66 })
67 })
68 }
69 }
70​
71 protected onUnsubscribe(): void {
72 if (!this.listeners.size) {
73 this.destroy()
74 }
75 }
76​
77 destroy(): void {
78 this.listeners = new Set()
79 this.#observers.forEach((observer) => {
80 observer.destroy()
81 })
82 }
83​
84 setQueries(
85 queries: Array<QueryObserverOptions>,
86 _options?: QueriesObserverOptions<TCombinedResult>,
87 notifyOptions?: NotifyOptions,
88 ): void {
89 this.#queries = queries
90​
91 notifyManager.batch(() => {
92 const prevObservers = this.#observers
93​
94 const newObserverMatches = this.#findMatchingObservers(this.#queries)
95​
96 // set options for the new observers to notify of changes
97 newObserverMatches.forEach((match) =>
98 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
99 )
100​
101 const newObservers = newObserverMatches.map((match) => match.observer)
102 const newResult = newObservers.map((observer) =>
103 observer.getCurrentResult(),
104 )
105​
106 const hasIndexChange = newObservers.some(
107 (observer, index) => observer !== prevObservers[index],
108 )
109​
110 if (prevObservers.length === newObservers.length && !hasIndexChange) {
111 return
112 }
113​
114 this.#observers = newObservers
115 this.#result = newResult
116​
117 if (!this.hasListeners()) {
118 return
119 }
120​
121 difference(prevObservers, newObservers).forEach((observer) => {
122 observer.destroy()
123 })
124​
125 difference(newObservers, prevObservers).forEach((observer) => {
126 observer.subscribe((result) => {
127 this.#onUpdate(observer, result)
128 })
129 })
130​
131 this.#notify()
132 })
133 }
134​
135 getCurrentResult(): Array<QueryObserverResult> {
136 return this.#result
137 }
138​
139 getQueries() {
140 return this.#observers.map((observer) => observer.getCurrentQuery())
141 }
142​
143 getObservers() {
144 return this.#observers
145 }
146​
147 getOptimisticResult(
148 queries: Array<QueryObserverOptions>,
149 combine: CombineFn<TCombinedResult> | undefined,
150 ): [
151 rawResult: Array<QueryObserverResult>,
152 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
153 trackResult: () => Array<QueryObserverResult>,
154 ] {
155 const matches = this.#findMatchingObservers(queries)
156 const result = matches.map((match) =>
157 match.observer.getOptimisticResult(match.defaultedQueryOptions),
158 )
159​
160 return [
161 result,
162 (r?: Array<QueryObserverResult>) => {
163 return this.#combineResult(r ?? result, combine)
164 },
165 () => {
166 return matches.map((match, index) => {
167 const observerResult = result[index]!
168 return !match.defaultedQueryOptions.notifyOnChangeProps
169 ? match.observer.trackResult(observerResult, (accessedProp) => {
170 // track property on all observers to ensure proper (synchronized) tracking (#7000)
171 matches.forEach((m) => {
172 m.observer.trackProp(accessedProp)
173 })
174 })
175 : observerResult
176 })
177 },
178 ]
179 }
180​
181 #combineResult(
182 input: Array<QueryObserverResult>,
183 combine: CombineFn<TCombinedResult> | undefined,
184 ): TCombinedResult {
185 if (combine) {
186 if (
187 !this.#combinedResult ||
188 this.#result !== this.#lastResult ||
189 combine !== this.#lastCombine
190 ) {
191 this.#lastCombine = combine
192 this.#lastResult = this.#result
193 this.#combinedResult = replaceEqualDeep(
194 this.#combinedResult,
195 combine(input),
196 )
197 }
198​
199 return this.#combinedResult
200 }
201 return input as any
202 }
203​
204 #findMatchingObservers(
205 queries: Array<QueryObserverOptions>,
206 ): Array<QueryObserverMatch> {
207 const prevObservers = this.#observers
208 const prevObserversMap = new Map(
209 prevObservers.map((observer) => [observer.options.queryHash, observer]),
210 )
211​
212 const defaultedQueryOptions = queries.map((options) =>
213 this.#client.defaultQueryOptions(options),
214 )
215​
216 const matchingObservers: Array<QueryObserverMatch> =
217 defaultedQueryOptions.flatMap((defaultedOptions) => {
218 const match = prevObserversMap.get(defaultedOptions.queryHash)
219 if (match != null) {
220 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
221 }
222 return []
223 })
224​
225 const matchedQueryHashes = new Set(
226 matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),
227 )
228 const unmatchedQueries = defaultedQueryOptions.filter(
229 (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),
230 )
231​
232 const getObserver = (options: QueryObserverOptions): QueryObserver => {
233 const defaultedOptions = this.#client.defaultQueryOptions(options)
234 const currentObserver = this.#observers.find(
235 (o) => o.options.queryHash === defaultedOptions.queryHash,
236 )
237 return (
238 currentObserver ?? new QueryObserver(this.#client, defaultedOptions)
239 )
240 }
241​
242 const newOrReusedObservers: Array<QueryObserverMatch> =
243 unmatchedQueries.map((options) => {
244 return {
245 defaultedQueryOptions: options,
246 observer: getObserver(options),
247 }
248 })
249​
250 const sortMatchesByOrderOfQueries = (
251 a: QueryObserverMatch,
252 b: QueryObserverMatch,
253 ): number =>
254 defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -
255 defaultedQueryOptions.indexOf(b.defaultedQueryOptions)
256​
257 return matchingObservers
258 .concat(newOrReusedObservers)
259 .sort(sortMatchesByOrderOfQueries)
260 }
261​
262 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
263 const index = this.#observers.indexOf(observer)
264 if (index !== -1) {
265 this.#result = replaceAt(this.#result, index, result)
266 this.#notify()
267 }
268 }
269​
270 #notify(): void {
271 notifyManager.batch(() => {
272 this.listeners.forEach((listener) => {
273 listener(this.#result)
274 })
275 })
276 }
278​
279type QueryObserverMatch = {
280 defaultedQueryOptions: DefaultedQueryObserverOptions
281 observer: QueryObserver