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

subscribable.ts

30 lines557 Bytes

1export class Subscribable<TListener extends Function> {
2 protected listeners = new Set<TListener>()
3​
4 constructor() {
5 this.subscribe = this.subscribe.bind(this)
6 }
7​
8 subscribe(listener: TListener): () => void {
9 this.listeners.add(listener)
10​
11 this.onSubscribe()
12​
13 return () => {
14 this.listeners.delete(listener)
15 this.onUnsubscribe()
16 }
17 }
18​
19 hasListeners(): boolean {
20 return this.listeners.size > 0
21 }
22​
23 protected onSubscribe(): void {
24 // Do nothing
25 }
26​
27 protected onUnsubscribe(): void {
28 // Do nothing
29 }