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

queriesObserver.ts

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