import { DataCache , CacheListener } from '@jdl2/cache' ; import { IObservable , action , observable , ObservableMap } from 'mobx' ; /**
 * Basic callback when eviction is called on an actively viewed entry
 */ export type EvictionCallback = ( key : string ) => void ; /**
 * Creates a new CacheListener that prevents actively viewed data from being
 * evicted by the cache and will call back to the listener when eviction is called
 */ export class MobxCacheListener < V > implements CacheListener < V > { cache : DataCache < V > ; @ observable _entries = new ObservableMap < string , V > ( ) ; onActiveDataEviction : EvictionCallback ; constructor ( cache , onActiveDataEviction ) { this . cache = cache ; this . onActiveDataEviction = onActiveDataEviction ; this . cache . addListener ( this ) ; } retrieved ( key , value ) { return this . _entries . get ( key ) ; } @ action added ( key , value ) { this . _entries . set ( key , value ) ; } @ action removed ( key , value ) { this . _entries . delete ( key ) ; } @ action evicted ( key , value ) { const o = ( this . _entries as any ) . _data . get ( key ) as IObservable ; if ( o && o . isBeingObserved ) { this . onActiveDataEviction ( key ) ; this . cache . _set ( key , value ) ; return ; } this . _entries . delete ( key ) ; } }