import { BehaviorSubject } from 'rxjs'; import { IStore } from './IStore'; import { proxyToBehaviorSubject } from './proxyToBehaviorSubject'; import { onFirstSubscription } from './onFirstSubscription'; export class ValueStore implements IStore { state$: BehaviorSubject; get state() { return this.state$.value; } constructor(value: Value) { const subject$ = new BehaviorSubject(value); this.state$ = proxyToBehaviorSubject( subject$.pipe( onFirstSubscription( () => this.onSubscribe(), () => this.onUnsubscribe() ) ), subject$ ); } setState(value: Value) { this.state$.next(value); } /** * This callback is called when the first subscriber subscribes to this store. * It may be called multiple times during the lifetime of the store. * You can use it to perform side-effects like subscribing to other * observables. */ onSubscribe() {} /** * This callback is called when the last subscriber unsubscribes from this store. * It may be called multiple times during the lifetime of the store. * You can use it to cleanup side-effects created during onSubscribe. */ onUnsubscribe() {} }