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 hasIndexChange = newObservers.some(
122 (observer, index) => observer !== prevObservers[index],
123 )
124β
125 const hasResultChange =
126 prevObservers.length === newObservers.length && !hasIndexChange
127 ? newResult.some((result, index) => {
128 const prev = this.#result[index]
129 return !prev || !shallowEqualObjects(result, prev)
130 })
131 : true
132β
133 if (!hasIndexChange && !hasResultChange) return
134β
135 if (hasIndexChange) {
136 this.#observers = newObservers
137 }
138β
139 this.#result = newResult
140β
141 if (!this.hasListeners()) return
142β
143 if (hasIndexChange) {
144 difference(prevObservers, newObservers).forEach((observer) => {
145 observer.destroy()
146 })
147 difference(newObservers, prevObservers).forEach((observer) => {
148 observer.subscribe((result) => {
149 this.#onUpdate(observer, result)
150 })
151 })
152 }
153β
154 this.#notify()
155 })
156 }
157β
158 getCurrentResult(): Array<QueryObserverResult> {
159 return this.#result
160 }
161β
162 getQueries() {
163 return this.#observers.map((observer) => observer.getCurrentQuery())
164 }
165β
166 getObservers() {
167 return this.#observers
168 }
169β
170 getOptimisticResult(
171 queries: Array<QueryObserverOptions>,
172 combine: CombineFn<TCombinedResult> | undefined,
173 ): [
174 rawResult: Array<QueryObserverResult>,
175 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
176 trackResult: () => Array<QueryObserverResult>,
177 ] {
178 const matches = this.#findMatchingObservers(queries)
179 const result = matches.map((match) =>
180 match.observer.getOptimisticResult(match.defaultedQueryOptions),
181 )
182β
183 return [
184 result,
185 (r?: Array<QueryObserverResult>) => {
186 return this.#combineResult(r ?? result, combine)
187 },
188 () => {
189 return this.#trackResult(result, matches)
190 },
191 ]
192 }
193β
194 #trackResult(
195 result: Array<QueryObserverResult>,
196 matches: Array<QueryObserverMatch>,
197 ) {
198 return matches.map((match, index) => {
199 const observerResult = result[index]!
200 return !match.defaultedQueryOptions.notifyOnChangeProps
201 ? match.observer.trackResult(observerResult, (accessedProp) => {
202 // track property on all observers to ensure proper (synchronized) tracking (#7000)
203 matches.forEach((m) => {
204 m.observer.trackProp(accessedProp)
205 })
206 })
207 : observerResult
208 })
209 }
210β
211 #combineResult(
212 input: Array<QueryObserverResult>,
213 combine: CombineFn<TCombinedResult> | undefined,
214 ): TCombinedResult {
215 if (combine) {
216 if (
217 !this.#combinedResult ||
218 this.#result !== this.#lastResult ||
219 combine !== this.#lastCombine
220 ) {
221 this.#lastCombine = combine
222 this.#lastResult = this.#result
223 this.#combinedResult = replaceEqualDeep(
224 this.#combinedResult,
225 combine(input),
226 )
227 }
228β
229 return this.#combinedResult
230 }
231 return input as any
232 }
233β
234 #findMatchingObservers(
235 queries: Array<QueryObserverOptions>,
236 ): Array<QueryObserverMatch> {
237 const prevObserversMap = new Map(
238 this.#observers.map((observer) => [observer.options.queryHash, observer]),
239 )
240β
241 const observers: Array<QueryObserverMatch> = []
242β
243 queries.forEach((options) => {
244 const defaultedOptions = this.#client.defaultQueryOptions(options)
245 const match = prevObserversMap.get(defaultedOptions.queryHash)
246 if (match) {
247 observers.push({
248 defaultedQueryOptions: defaultedOptions,
249 observer: match,
250 })
251 } else {
252 observers.push({
253 defaultedQueryOptions: defaultedOptions,
254 observer: new QueryObserver(this.#client, defaultedOptions),
255 })
256 }
257 })
258β
259 return observers
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 if (this.hasListeners()) {
272 const previousResult = this.#combinedResult
273 const newTracked = this.#trackResult(this.#result, this.#observerMatches)
274 const newResult = this.#combineResult(newTracked, this.#options?.combine)
275β
276 if (previousResult !== newResult) {
277 notifyManager.batch(() => {
278 this.listeners.forEach((listener) => {
279 listener(this.#result)
280 })
281 })
282 }
283 }
284 }
285}
286β
287type QueryObserverMatch = {
288 defaultedQueryOptions: DefaultedQueryObserverOptions
289 observer: QueryObserver
290}