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

queriesObserver.ts

210 lines6.0 KB

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