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