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

subscribable.ts

62 lines1.9 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 * @returns A function that removes the listener.
19 * @example
20 * ```ts
21 * const unsubscribe = subscribable.subscribe(() => {
22 * // react to the update
23 * })
24 *
25 * unsubscribe()
26 * ```
27 */
28 subscribe(listener: TListener): () => void {
29 this.listeners.add(listener)
30​
31 this.onSubscribe()
32​
33 return () => {
34 this.listeners.delete(listener)
35 this.onUnsubscribe()
36 }
37 }
38​
39 /**
40 * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
41 * @returns `true` if at least one listener is registered.
42 */
43 hasListeners(): boolean {
44 return this.listeners.size > 0
45 }
46​
47 /**
48 * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start
49 * tracking what they observe once the first listener subscribes.
50 */
51 protected onSubscribe(): void {
52 // Do nothing
53 }
54​
55 /**
56 * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up
57 * once the last listener unsubscribes.
58 */
59 protected onUnsubscribe(): void {
60 // Do nothing
61 }