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

subscribable.ts

65 lines2.1 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<
7 // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject
8 TListener extends Function,
9> {
10 protected listeners = new Set<TListener>()
11​
12 constructor() {
13 this.subscribe = this.subscribe.bind(this)
14 }
15​
16 /**
17 * Registers a listener to be called on every update this object notifies about. Returns a function
18 * that removes the listener again β€” call it to stop listening. The base class never drops a listener
19 * on its own, though some subclasses clear all of theirs in `destroy()`.
20 * @param listener - Called on each update, with whatever the subclass passes to its subscribers.
21 * @returns A function that removes the listener.
22 * @example
23 * ```ts
24 * const unsubscribe = subscribable.subscribe(() => {
25 * // react to the update
26 * })
27 *
28 * unsubscribe()
29 * ```
30 */
31 subscribe(listener: TListener): () => void {
32 this.listeners.add(listener)
33​
34 this.onSubscribe()
35​
36 return () => {
37 this.listeners.delete(listener)
38 this.onUnsubscribe()
39 }
40 }
41​
42 /**
43 * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
44 * @returns `true` if at least one listener is registered.
45 */
46 hasListeners(): boolean {
47 return this.listeners.size > 0
48 }
49​
50 /**
51 * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start
52 * tracking what they observe once the first listener subscribes.
53 */
54 protected onSubscribe(): void {
55 // Do nothing
56 }
57​
58 /**
59 * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up
60 * once the last listener unsubscribes.
61 */
62 protected onUnsubscribe(): void {
63 // Do nothing
64 }