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

queriesObserver.ts

291 lines8.0 KB

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