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

subscribable.ts

34 lines660 Bytes

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