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

queriesObserver.ts

262 lines7.0 KB

1import { notifyManager } from './notifyManager'
2import type {
3 QueryObserverOptions,
4 QueryObserverResult,
5 DefaultedQueryObserverOptions,
6} from './types'
7import type { QueryClient } from './queryClient'
8import type { NotifyOptions } from './queryObserver'
9import { QueryObserver } from './queryObserver'
10import { Subscribable } from './subscribable'
11import { replaceEqualDeep } from './utils'
12​
13function difference<T>(array1: T[], array2: T[]): T[] {
14 return array1.filter((x) => array2.indexOf(x) === -1)
16​
17function replaceAt<T>(array: T[], index: number, value: T): T[] {
18 const copy = array.slice(0)
19 copy[index] = value
20 return copy
22​
23type QueriesObserverListener = (result: QueryObserverResult[]) => void
24​
25export interface QueriesObserverOptions<
26 TCombinedResult = QueryObserverResult[],
27> {
28 combine?: (result: QueryObserverResult[]) => TCombinedResult
30​
31export class QueriesObserver<
32 TCombinedResult = QueryObserverResult[],
33> extends Subscribable<QueriesObserverListener> {
34 #client: QueryClient
35 #result!: QueryObserverResult[]
36 #queries: QueryObserverOptions[]
37 #observers: QueryObserver[]
38 #options?: QueriesObserverOptions<TCombinedResult>
39 #combinedResult!: TCombinedResult
40​
41 constructor(
42 client: QueryClient,
43 queries: 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: 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: 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 if (prevObservers.length === newObservers.length && !hasIndexChange) {
111 return
112 }
113​
114 this.#observers = newObservers
115 this.#setResult(newResult)
116​
117 if (!this.hasListeners()) {
118 return
119 }
120​
121 difference(prevObservers, newObservers).forEach((observer) => {
122 observer.destroy()
123 })
124​
125 difference(newObservers, prevObservers).forEach((observer) => {
126 observer.subscribe((result) => {
127 this.#onUpdate(observer, result)
128 })
129 })
130​
131 this.#notify()
132 })
133 }
134​
135 getCurrentResult(): TCombinedResult {
136 return this.#combinedResult
137 }
138​
139 getQueries() {
140 return this.#observers.map((observer) => observer.getCurrentQuery())
141 }
142​
143 getObservers() {
144 return this.#observers
145 }
146​
147 getOptimisticResult(
148 queries: QueryObserverOptions[],
149 ): [
150 rawResult: QueryObserverResult[],
151 combineResult: (r?: QueryObserverResult[]) => TCombinedResult,
152 trackResult: () => QueryObserverResult[],
153 ] {
154 const matches = this.#findMatchingObservers(queries)
155 const result = matches.map((match) =>
156 match.observer.getOptimisticResult(match.defaultedQueryOptions),
157 )
158​
159 return [
160 result,
161 (r?: QueryObserverResult[]) => {
162 return this.#combineResult(r ?? result)
163 },
164 () => {
165 return matches.map((match, index) => {
166 const observerResult = result[index]!
167 return !match.defaultedQueryOptions.notifyOnChangeProps
168 ? match.observer.trackResult(observerResult)
169 : observerResult
170 })
171 },
172 ]
173 }
174​
175 #combineResult(input: QueryObserverResult[]): TCombinedResult {
176 const combine = this.#options?.combine
177 if (combine) {
178 return replaceEqualDeep(this.#combinedResult, combine(input))
179 }
180 return input as any
181 }
182​
183 #findMatchingObservers(
184 queries: QueryObserverOptions[],
185 ): QueryObserverMatch[] {
186 const prevObservers = this.#observers
187 const prevObserversMap = new Map(
188 prevObservers.map((observer) => [observer.options.queryHash, observer]),
189 )
190​
191 const defaultedQueryOptions = queries.map((options) =>
192 this.#client.defaultQueryOptions(options),
193 )
194​
195 const matchingObservers: QueryObserverMatch[] =
196 defaultedQueryOptions.flatMap((defaultedOptions) => {
197 const match = prevObserversMap.get(defaultedOptions.queryHash)
198 if (match != null) {
199 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
200 }
201 return []
202 })
203​
204 const matchedQueryHashes = new Set(
205 matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),
206 )
207 const unmatchedQueries = defaultedQueryOptions.filter(
208 (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),
209 )
210​
211 const getObserver = (options: QueryObserverOptions): QueryObserver => {
212 const defaultedOptions = this.#client.defaultQueryOptions(options)
213 const currentObserver = this.#observers.find(
214 (o) => o.options.queryHash === defaultedOptions.queryHash,
215 )
216 return (
217 currentObserver ?? new QueryObserver(this.#client, defaultedOptions)
218 )
219 }
220​
221 const newOrReusedObservers: QueryObserverMatch[] = unmatchedQueries.map(
222 (options) => {
223 return {
224 defaultedQueryOptions: options,
225 observer: getObserver(options),
226 }
227 },
228 )
229​
230 const sortMatchesByOrderOfQueries = (
231 a: QueryObserverMatch,
232 b: QueryObserverMatch,
233 ): number =>
234 defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -
235 defaultedQueryOptions.indexOf(b.defaultedQueryOptions)
236​
237 return matchingObservers
238 .concat(newOrReusedObservers)
239 .sort(sortMatchesByOrderOfQueries)
240 }
241​
242 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
243 const index = this.#observers.indexOf(observer)
244 if (index !== -1) {
245 this.#setResult(replaceAt(this.#result, index, result))
246 this.#notify()
247 }
248 }
249​
250 #notify(): void {
251 notifyManager.batch(() => {
252 this.listeners.forEach((listener) => {
253 listener(this.#result)
254 })
255 })
256 }
258​
259type QueryObserverMatch = {
260 defaultedQueryOptions: DefaultedQueryObserverOptions
261 observer: QueryObserver