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

queriesObserver.ts

211 lines5.9 KB

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