import { SubscribeFunction } from '../types' ; export interface IObserverManager { isSubscribed ( observerName ) : boolean ; register ( observerName , subscribe ) : void ; unsubscribe ( observerName ) : boolean ; } interface ObserverInfo { unsubscribe : Function ; numberOfListeners : number ; } class ObserverManager { private static instance : IObserverManager ; private subscribedObservers : Record < string , ObserverInfo > ; constructor ( ) { this . subscribedObservers = { } ; } public static getInstance ( ) { if ( ! ObserverManager . instance ) { ObserverManager . instance = new ObserverManager ( ) ; } return ObserverManager . instance ; } public isSubscribed = ( observerName ) : boolean => ! ! this . subscribedObservers [ observerName ] ; public unsubscribe = ( observerName ) : boolean => { if ( ! this . subscribedObservers [ observerName ] ) { return false ; } this . subscribedObservers [ observerName ] . numberOfListeners -= 1 ; if ( this . subscribedObservers [ observerName ] . numberOfListeners <= 0 ) { this . subscribedObservers [ observerName ] . unsubscribe ( ) ; return true ; } return false ; } ; public register = ( observerName , subscribe ) => { if ( this . isSubscribed ( observerName ) ) { this . subscribedObservers [ observerName ] . numberOfListeners += 1 ; return ; } const unsubscribe = subscribe ( ) ; this . subscribedObservers [ observerName ] = { numberOfListeners : 1 , unsubscribe , } ; } ; } export default ObserverManager ;