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β
47 constructor(
48 client: QueryClient,
49 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
50 options?: QueriesObserverOptions<TCombinedResult>,
51 ) {
52 super()
53β
54 this.#client = client
55 this.#options = options
56 this.#queries = []
57 this.#observers = []
58 this.#result = []
59β
60 this.setQueries(queries)
61 }
62β
63 protected onSubscribe(): void {
64 if (this.listeners.size === 1) {
65 this.#observers.forEach((observer) => {
66 observer.subscribe((result) => {
67 this.#onUpdate(observer, result)
68 })
69 })
70 }
71 }
72β
73 protected onUnsubscribe(): void {
74 if (!this.listeners.size) {
75 this.destroy()
76 }
77 }
78β
79 destroy(): void {
80 this.listeners = new Set()
81 this.#observers.forEach((observer) => {
82 observer.destroy()
83 })
84 }
85β
86 setQueries(
87 queries: Array<QueryObserverOptions>,
88 options?: QueriesObserverOptions<TCombinedResult>,
89 notifyOptions?: NotifyOptions,
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β
110 // set options for the new observers to notify of changes
111 newObserverMatches.forEach((match) =>
112 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
113 )
114β
115 const newObservers = newObserverMatches.map((match) => match.observer)
116 const newResult = newObservers.map((observer) =>
117 observer.getCurrentResult(),
118 )
119β
120 const hasIndexChange = newObservers.some(
121 (observer, index) => observer !== prevObservers[index],
122 )
123β
124 if (prevObservers.length === newObservers.length && !hasIndexChange) {
125 return
126 }
127β
128 this.#observers = newObservers
129 this.#result = newResult
130β
131 if (!this.hasListeners()) {
132 return
133 }
134β
135 difference(prevObservers, newObservers).forEach((observer) => {
136 observer.destroy()
137 })
138β
139 difference(newObservers, prevObservers).forEach((observer) => {
140 observer.subscribe((result) => {
141 this.#onUpdate(observer, result)
142 })
143 })
144β
145 this.#notify()
146 })
147 }
148β
149 getCurrentResult(): Array<QueryObserverResult> {
150 return this.#result
151 }
152β
153 getQueries() {
154 return this.#observers.map((observer) => observer.getCurrentQuery())
155 }
156β
157 getObservers() {
158 return this.#observers
159 }
160β
161 getOptimisticResult(
162 queries: Array<QueryObserverOptions>,
163 combine: CombineFn<TCombinedResult> | undefined,
164 ): [
165 rawResult: Array<QueryObserverResult>,
166 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
167 trackResult: () => Array<QueryObserverResult>,
168 ] {
169 const matches = this.#findMatchingObservers(queries)
170 const result = matches.map((match) =>
171 match.observer.getOptimisticResult(match.defaultedQueryOptions),
172 )
173β
174 return [
175 result,
176 (r?: Array<QueryObserverResult>) => {
177 return this.#combineResult(r ?? result, combine)
178 },
179 () => {
180 return this.#trackResult(result, queries)
181 },
182 ]
183 }
184β
185 #trackResult(
186 result: Array<QueryObserverResult>,
187 queries: Array<QueryObserverOptions>,
188 ) {
189 const matches = this.#findMatchingObservers(queries)
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 newResult = this.#combineResult(
267 this.#trackResult(this.#result, this.#queries),
268 this.#options?.combine,
269 )
270β
271 if (previousResult !== newResult) {
272 notifyManager.batch(() => {
273 this.listeners.forEach((listener) => {
274 listener(this.#result)
275 })
276 })
277 }
278 }
279 }
280}
281β
282type QueryObserverMatch = {
283 defaultedQueryOptions: DefaultedQueryObserverOptions
284 observer: QueryObserver
285}