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