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

queriesObserver.ts

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