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

queriesObserver.ts

269 lines7.3 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'
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))
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
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>
34​
35export class QueriesObserver<
36 TCombinedResult = Array<QueryObserverResult>,
37> extends Subscribable<QueriesObserverListener> {
38 #client: QueryClient
39 #result!: Array<QueryObserverResult>
40 #queries: Array<QueryObserverOptions>
41 #observers: Array<QueryObserver>
42 #options?: QueriesObserverOptions<TCombinedResult>
43 #combinedResult!: TCombinedResult
44​
45 constructor(
46 client: QueryClient,
47 queries: Array<QueryObserverOptions>,
48 options?: QueriesObserverOptions<TCombinedResult>,
49 ) {
50 super()
51​
52 this.#client = client
53 this.#queries = []
54 this.#observers = []
55​
56 this.#setResult([])
57 this.setQueries(queries, options)
58 }
59​
60 #setResult(value: Array<QueryObserverResult>) {
61 this.#result = value
62 this.#combinedResult = this.#combineResult(value, this.#options?.combine)
63 }
64​
65 protected onSubscribe(): void {
66 if (this.listeners.size === 1) {
67 this.#observers.forEach((observer) => {
68 observer.subscribe((result) => {
69 this.#onUpdate(observer, result)
70 })
71 })
72 }
73 }
74​
75 protected onUnsubscribe(): void {
76 if (!this.listeners.size) {
77 this.destroy()
78 }
79 }
80​
81 destroy(): void {
82 this.listeners = new Set()
83 this.#observers.forEach((observer) => {
84 observer.destroy()
85 })
86 }
87​
88 setQueries(
89 queries: Array<QueryObserverOptions>,
90 options?: QueriesObserverOptions<TCombinedResult>,
91 notifyOptions?: NotifyOptions,
92 ): void {
93 this.#queries = queries
94 this.#options = options
95​
96 notifyManager.batch(() => {
97 const prevObservers = this.#observers
98​
99 const newObserverMatches = this.#findMatchingObservers(this.#queries)
100​
101 // set options for the new observers to notify of changes
102 newObserverMatches.forEach((match) =>
103 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
104 )
105​
106 const newObservers = newObserverMatches.map((match) => match.observer)
107 const newResult = newObservers.map((observer) =>
108 observer.getCurrentResult(),
109 )
110​
111 const hasIndexChange = newObservers.some(
112 (observer, index) => observer !== prevObservers[index],
113 )
114​
115 if (prevObservers.length === newObservers.length && !hasIndexChange) {
116 return
117 }
118​
119 this.#observers = newObservers
120 this.#setResult(newResult)
121​
122 if (!this.hasListeners()) {
123 return
124 }
125​
126 difference(prevObservers, newObservers).forEach((observer) => {
127 observer.destroy()
128 })
129​
130 difference(newObservers, prevObservers).forEach((observer) => {
131 observer.subscribe((result) => {
132 this.#onUpdate(observer, result)
133 })
134 })
135​
136 this.#notify()
137 })
138 }
139​
140 getCurrentResult(): TCombinedResult {
141 return this.#combinedResult
142 }
143​
144 getQueries() {
145 return this.#observers.map((observer) => observer.getCurrentQuery())
146 }
147​
148 getObservers() {
149 return this.#observers
150 }
151​
152 getOptimisticResult(
153 queries: Array<QueryObserverOptions>,
154 combine: CombineFn<TCombinedResult> | undefined,
155 ): [
156 rawResult: Array<QueryObserverResult>,
157 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
158 trackResult: () => Array<QueryObserverResult>,
159 ] {
160 const matches = this.#findMatchingObservers(queries)
161 const result = matches.map((match) =>
162 match.observer.getOptimisticResult(match.defaultedQueryOptions),
163 )
164​
165 return [
166 result,
167 (r?: Array<QueryObserverResult>) => {
168 return this.#combineResult(r ?? result, combine)
169 },
170 () => {
171 return matches.map((match, index) => {
172 const observerResult = result[index]!
173 return !match.defaultedQueryOptions.notifyOnChangeProps
174 ? match.observer.trackResult(observerResult)
175 : observerResult
176 })
177 },
178 ]
179 }
180​
181 #combineResult(
182 input: Array<QueryObserverResult>,
183 combine: CombineFn<TCombinedResult> | undefined,
184 ): TCombinedResult {
185 if (combine) {
186 return replaceEqualDeep(this.#combinedResult, combine(input))
187 }
188 return input as any
189 }
190​
191 #findMatchingObservers(
192 queries: Array<QueryObserverOptions>,
193 ): Array<QueryObserverMatch> {
194 const prevObservers = this.#observers
195 const prevObserversMap = new Map(
196 prevObservers.map((observer) => [observer.options.queryHash, observer]),
197 )
198​
199 const defaultedQueryOptions = queries.map((options) =>
200 this.#client.defaultQueryOptions(options),
201 )
202​
203 const matchingObservers: Array<QueryObserverMatch> =
204 defaultedQueryOptions.flatMap((defaultedOptions) => {
205 const match = prevObserversMap.get(defaultedOptions.queryHash)
206 if (match != null) {
207 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
208 }
209 return []
210 })
211​
212 const matchedQueryHashes = new Set(
213 matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),
214 )
215 const unmatchedQueries = defaultedQueryOptions.filter(
216 (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),
217 )
218​
219 const getObserver = (options: QueryObserverOptions): QueryObserver => {
220 const defaultedOptions = this.#client.defaultQueryOptions(options)
221 const currentObserver = this.#observers.find(
222 (o) => o.options.queryHash === defaultedOptions.queryHash,
223 )
224 return (
225 currentObserver ?? new QueryObserver(this.#client, defaultedOptions)
226 )
227 }
228​
229 const newOrReusedObservers: Array<QueryObserverMatch> =
230 unmatchedQueries.map((options) => {
231 return {
232 defaultedQueryOptions: options,
233 observer: getObserver(options),
234 }
235 })
236​
237 const sortMatchesByOrderOfQueries = (
238 a: QueryObserverMatch,
239 b: QueryObserverMatch,
240 ): number =>
241 defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -
242 defaultedQueryOptions.indexOf(b.defaultedQueryOptions)
243​
244 return matchingObservers
245 .concat(newOrReusedObservers)
246 .sort(sortMatchesByOrderOfQueries)
247 }
248​
249 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
250 const index = this.#observers.indexOf(observer)
251 if (index !== -1) {
252 this.#setResult(replaceAt(this.#result, index, result))
253 this.#notify()
254 }
255 }
256​
257 #notify(): void {
258 notifyManager.batch(() => {
259 this.listeners.forEach((listener) => {
260 listener(this.#result)
261 })
262 })
263 }
265​
266type QueryObserverMatch = {
267 defaultedQueryOptions: DefaultedQueryObserverOptions
268 observer: QueryObserver