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

subscribable.ts

33 lines656 Bytes

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