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

queriesObserver.ts

222 lines6.3 KB

1import { difference, replaceAt } from './utils'
2import { notifyManager } from './notifyManager'
3import { QueryObserver } from './queryObserver'
4import { Subscribable } from './subscribable'
5import type {
6 DefaultedQueryObserverOptions,
7 QueryObserverOptions,
8 QueryObserverResult,
9} from './types'
10import type { QueryClient } from './queryClient'
11import type { NotifyOptions } from './queryObserver'
12​
13type QueriesObserverListener = (result: QueryObserverResult[]) => void
14​
15export class QueriesObserver extends Subscribable<QueriesObserverListener> {
16 private client: QueryClient
17 private result: QueryObserverResult[]
18 private queries: QueryObserverOptions[]
19 private observers: QueryObserver[]
20 private observersMap: Record<string, QueryObserver>
21​
22 constructor(client: QueryClient, queries?: QueryObserverOptions[]) {
23 super()
24​
25 this.client = client
26 this.queries = []
27 this.result = []
28 this.observers = []
29 this.observersMap = {}
30​
31 if (queries) {
32 this.setQueries(queries)
33 }
34 }
35​
36 protected onSubscribe(): void {
37 if (this.listeners.size === 1) {
38 this.observers.forEach((observer) => {
39 observer.subscribe((result) => {
40 this.onUpdate(observer, result)
41 })
42 })
43 }
44 }
45​
46 protected onUnsubscribe(): void {
47 if (!this.listeners.size) {
48 this.destroy()
49 }
50 }
51​
52 destroy(): void {
53 this.listeners = new Set()
54 this.observers.forEach((observer) => {
55 observer.destroy()
56 })
57 }
58​
59 setQueries(
60 queries: QueryObserverOptions[],
61 notifyOptions?: NotifyOptions,
62 ): void {
63 this.queries = queries
64​
65 notifyManager.batch(() => {
66 const prevObservers = this.observers
67​
68 const newObserverMatches = this.findMatchingObservers(this.queries)
69​
70 // set options for the new observers to notify of changes
71 newObserverMatches.forEach((match) =>
72 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
73 )
74​
75 const newObservers = newObserverMatches.map((match) => match.observer)
76 const newObserversMap = Object.fromEntries(
77 newObservers.map((observer) => [observer.options.queryHash, observer]),
78 )
79 const newResult = newObservers.map((observer) =>
80 observer.getCurrentResult(),
81 )
82​
83 const hasIndexChange = newObservers.some(
84 (observer, index) => observer !== prevObservers[index],
85 )
86 if (prevObservers.length === newObservers.length && !hasIndexChange) {
87 return
88 }
89​
90 this.observers = newObservers
91 this.observersMap = newObserversMap
92 this.result = newResult
93​
94 if (!this.hasListeners()) {
95 return
96 }
97​
98 difference(prevObservers, newObservers).forEach((observer) => {
99 observer.destroy()
100 })
101​
102 difference(newObservers, prevObservers).forEach((observer) => {
103 observer.subscribe((result) => {
104 this.onUpdate(observer, result)
105 })
106 })
107​
108 this.notify()
109 })
110 }
111​
112 getCurrentResult(): QueryObserverResult[] {
113 return this.result
114 }
115​
116 getQueries() {
117 return this.observers.map((observer) => observer.getCurrentQuery())
118 }
119​
120 getObservers() {
121 return this.observers
122 }
123​
124 getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[] {
125 return this.findMatchingObservers(queries).map((match) =>
126 match.observer.getOptimisticResult(match.defaultedQueryOptions),
127 )
128 }
129​
130 private findMatchingObservers(
131 queries: QueryObserverOptions[],
132 ): QueryObserverMatch[] {
133 const prevObservers = this.observers
134 const prevObserversMap = new Map(
135 prevObservers.map((observer) => [observer.options.queryHash, observer]),
136 )
137​
138 const defaultedQueryOptions = queries.map((options) =>
139 this.client.defaultQueryOptions(options),
140 )
141​
142 const matchingObservers: QueryObserverMatch[] =
143 defaultedQueryOptions.flatMap((defaultedOptions) => {
144 const match = prevObserversMap.get(defaultedOptions.queryHash)
145 if (match != null) {
146 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
147 }
148 return []
149 })
150​
151 const matchedQueryHashes = new Set(
152 matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),
153 )
154 const unmatchedQueries = defaultedQueryOptions.filter(
155 (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),
156 )
157​
158 const matchingObserversSet = new Set(
159 matchingObservers.map((match) => match.observer),
160 )
161 const unmatchedObservers = prevObservers.filter(
162 (prevObserver) => !matchingObserversSet.has(prevObserver),
163 )
164​
165 const getObserver = (options: QueryObserverOptions): QueryObserver => {
166 const defaultedOptions = this.client.defaultQueryOptions(options)
167 const currentObserver = this.observersMap[defaultedOptions.queryHash!]
168 return currentObserver ?? new QueryObserver(this.client, defaultedOptions)
169 }
170​
171 const newOrReusedObservers: QueryObserverMatch[] = unmatchedQueries.map(
172 (options, index) => {
173 if (options.keepPreviousData) {
174 // return previous data from one of the observers that no longer match
175 const previouslyUsedObserver = unmatchedObservers[index]
176 if (previouslyUsedObserver !== undefined) {
177 return {
178 defaultedQueryOptions: options,
179 observer: previouslyUsedObserver,
180 }
181 }
182 }
183 return {
184 defaultedQueryOptions: options,
185 observer: getObserver(options),
186 }
187 },
188 )
189​
190 const sortMatchesByOrderOfQueries = (
191 a: QueryObserverMatch,
192 b: QueryObserverMatch,
193 ): number =>
194 defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -
195 defaultedQueryOptions.indexOf(b.defaultedQueryOptions)
196​
197 return matchingObservers
198 .concat(newOrReusedObservers)
199 .sort(sortMatchesByOrderOfQueries)
200 }
201​
202 private onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
203 const index = this.observers.indexOf(observer)
204 if (index !== -1) {
205 this.result = replaceAt(this.result, index, result)
206 this.notify()
207 }
208 }
209​
210 private notify(): void {
211 notifyManager.batch(() => {
212 this.listeners.forEach(({ listener }) => {
213 listener(this.result)
214 })
215 })
216 }
218​
219type QueryObserverMatch = {
220 defaultedQueryOptions: DefaultedQueryObserverOptions
221 observer: QueryObserver