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

subscribable.ts

34 lines668 Bytes

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