import { Callbag , Sink } from 'callbag' ; export const cachedSubject = < T > ( initial ) : Callbag < T , T > & { getValue : ( ) => T ; } => { let sinks = [ ] ; let latest = initial ; const newCachedSubject = ( type , data ) => { if ( type === 0 ) { const callbag = data ; sinks . push ( callbag ) ; callbag ( 0 , ( t ) => { if ( t === 2 ) { const i = sinks . indexOf ( data ) ; if ( - 1 < i ) { sinks . splice ( i , 1 ) ; } } } ) ; } else { if ( type === 1 ) { latest = data ; } let subs = sinks . slice ( 0 ) ; for ( let i = 0 , n = subs . length ; i < n ; i ++ ) { if ( - 1 < sinks . indexOf ( subs [ i ] ) ) { subs [ i ] ( 1 , data ) ; } } } } ; newCachedSubject . getValue = ( ) => latest ; return newCachedSubject ; } ;