Open History to see the last commit
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))
15}
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
21}
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>
33}
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 }
286}
287β
288type QueryObserverMatch = {
289 defaultedQueryOptions: DefaultedQueryObserverOptions
290 observer: QueryObserver
291}