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