Open History to see the last commit
1/**
2 * The base class behind everything in Query that you can subscribe to:
3 * `QueryCache`, `MutationCache`, the observers, and the
4 * `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`.
5 * Subclasses decide what a listener receives and when it is called.
6 */
7export class Subscribable<TListener extends Function> {
8 protected listeners = new Set<TListener>()
9β
10 constructor() {
11 this.subscribe = this.subscribe.bind(this)
12 }
13β
14 /**
15 * Registers a listener to be called on every update this object notifies
16 * about. Returns a function that removes the listener again β call it to stop
17 * listening. The base class never drops a listener on its own, though some
18 * subclasses clear all of theirs in `destroy()`.
19 *
20 * @example
21 * ;```ts
22 * const unsubscribe = subscribable.subscribe(() => {
23 * // react to the update
24 * })
25 *
26 * unsubscribe()
27 * ```
28 *
29 * @param listener - Called on each update, with whatever the subclass passes
30 * to its subscribers.
31 * @returns A function that removes the listener.
32 */
33 subscribe(listener: TListener): () => void {
34 this.listeners.add(listener)
35β
36 this.onSubscribe()
37β
38 return () => {
39 this.listeners.delete(listener)
40 this.onUnsubscribe()
41 }
42 }
43β
44 /**
45 * Returns `true` while at least one listener is registered, `false` once they
46 * have all unsubscribed.
47 *
48 * @returns `true` if at least one listener is registered.
49 */
50 hasListeners(): boolean {
51 return this.listeners.size > 0
52 }
53β
54 /**
55 * Called after a listener is added. Does nothing here; subclasses override
56 * it, e.g. to start tracking what they observe once the first listener
57 * subscribes.
58 */
59 protected onSubscribe(): void {
60 // Do nothing
61 }
62β
63 /**
64 * Called after a listener is removed. Does nothing here; subclasses override
65 * it, e.g. to clean up once the last listener unsubscribes.
66 */
67 protected onUnsubscribe(): void {
68 // Do nothing
69 }
70}