Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queriesObserver.ts

281 lines7.5 KB

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 return array1.filter((x) => !array2.includes(x))
15​
16function replaceAt<T>(array: Array<T>, index: number, value: T): Array<T> {
17 const copy = array.slice(0)
18 copy[index] = value
19 return copy
21​
22type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
23​
24type CombineFn<TCombinedResult> = (
25 result: Array<QueryObserverResult>,
26) => TCombinedResult
27​
28export interface QueriesObserverOptions<
29 TCombinedResult = Array<QueryObserverResult>,
30> {
31 combine?: CombineFn<TCombinedResult>
33​
34export class QueriesObserver<
35 TCombinedResult = Array<QueryObserverResult>,
36> extends Subscribable<QueriesObserverListener> {
37 #client: QueryClient
38 #result!: Array<QueryObserverResult>
39 #queries: Array<QueryObserverOptions>
40 #options?: QueriesObserverOptions<TCombinedResult>
41 #observers: Array<QueryObserver>
42 #combinedResult?: TCombinedResult
43 #lastCombine?: CombineFn<TCombinedResult>
44 #lastResult?: Array<QueryObserverResult>
45 #observerMatches: Array<QueryObserverMatch> = []
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 ): void {
90 this.#queries = queries
91 this.#options = options
92​
93 if (process.env.NODE_ENV !== 'production') {
94 const queryHashes = queries.map(
95 (query) => this.#client.defaultQueryOptions(query).queryHash,
96 )
97 if (new Set(queryHashes).size !== queryHashes.length) {
98 console.warn(
99 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
100 )
101 }
102 }
103​
104 notifyManager.batch(() => {
105 const prevObservers = this.#observers
106​
107 const newObserverMatches = this.#findMatchingObservers(this.#queries)
108 this.#observerMatches = newObserverMatches
109​
110 // set options for the new observers to notify of changes
111 newObserverMatches.forEach((match) =>
112 match.observer.setOptions(match.defaultedQueryOptions),
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, matches)
181 },
182 ]
183 }
184​
185 #trackResult(
186 result: Array<QueryObserverResult>,
187 matches: Array<QueryObserverMatch>,
188 ) {
189 return matches.map((match, index) => {
190 const observerResult = result[index]!
191 return !match.defaultedQueryOptions.notifyOnChangeProps
192 ? match.observer.trackResult(observerResult, (accessedProp) => {
193 // track property on all observers to ensure proper (synchronized) tracking (#7000)
194 matches.forEach((m) => {
195 m.observer.trackProp(accessedProp)
196 })
197 })
198 : observerResult
199 })
200 }
201​
202 #combineResult(
203 input: Array<QueryObserverResult>,
204 combine: CombineFn<TCombinedResult> | undefined,
205 ): TCombinedResult {
206 if (combine) {
207 if (
208 !this.#combinedResult ||
209 this.#result !== this.#lastResult ||
210 combine !== this.#lastCombine
211 ) {
212 this.#lastCombine = combine
213 this.#lastResult = this.#result
214 this.#combinedResult = replaceEqualDeep(
215 this.#combinedResult,
216 combine(input),
217 )
218 }
219​
220 return this.#combinedResult
221 }
222 return input as any
223 }
224​
225 #findMatchingObservers(
226 queries: Array<QueryObserverOptions>,
227 ): Array<QueryObserverMatch> {
228 const prevObserversMap = new Map(
229 this.#observers.map((observer) => [observer.options.queryHash, observer]),
230 )
231​
232 const observers: Array<QueryObserverMatch> = []
233​
234 queries.forEach((options) => {
235 const defaultedOptions = this.#client.defaultQueryOptions(options)
236 const match = prevObserversMap.get(defaultedOptions.queryHash)
237 if (match) {
238 observers.push({
239 defaultedQueryOptions: defaultedOptions,
240 observer: match,
241 })
242 } else {
243 observers.push({
244 defaultedQueryOptions: defaultedOptions,
245 observer: new QueryObserver(this.#client, defaultedOptions),
246 })
247 }
248 })
249​
250 return observers
251 }
252​
253 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
254 const index = this.#observers.indexOf(observer)
255 if (index !== -1) {
256 this.#result = replaceAt(this.#result, index, result)
257 this.#notify()
258 }
259 }
260​
261 #notify(): void {
262 if (this.hasListeners()) {
263 const previousResult = this.#combinedResult
264 const newTracked = this.#trackResult(this.#result, this.#observerMatches)
265 const newResult = this.#combineResult(newTracked, this.#options?.combine)
266​
267 if (previousResult !== newResult) {
268 notifyManager.batch(() => {
269 this.listeners.forEach((listener) => {
270 listener(this.#result)
271 })
272 })
273 }
274 }
275 }
277​
278type QueryObserverMatch = {
279 defaultedQueryOptions: DefaultedQueryObserverOptions
280 observer: QueryObserver