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

subscribable.ts

52 lines1.5 KB

1/**
2 * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`,
3 * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`.
4 * Subclasses decide what a listener receives and when it is called.
5 */
6export class Subscribable<TListener extends Function> {
7 protected listeners = new Set<TListener>()
8​
9 constructor() {
10 this.subscribe = this.subscribe.bind(this)
11 }
12​
13 /**
14 * Registers a listener to be called on every update this object notifies about. Returns a function
15 * that removes the listener again β€” call it to stop listening. The base class never drops a listener
16 * on its own, though some subclasses clear all of theirs in `destroy()`.
17 * @param listener - Called on each update, with whatever the subclass passes to its subscribers.
18 * @example
19 * ```ts
20 * const unsubscribe = subscribable.subscribe(() => {
21 * // react to the update
22 * })
23 *
24 * unsubscribe()
25 * ```
26 */
27 subscribe(listener: TListener): () => void {
28 this.listeners.add(listener)
29​
30 this.onSubscribe()
31​
32 return () => {
33 this.listeners.delete(listener)
34 this.onUnsubscribe()
35 }
36 }
37​
38 /**
39 * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
40 */
41 hasListeners(): boolean {
42 return this.listeners.size > 0
43 }
44​
45 protected onSubscribe(): void {
46 // Do nothing
47 }
48​
49 protected onUnsubscribe(): void {
50 // Do nothing
51 }