import { AngularFireAction , DatabaseQuery , DatabaseSnapshot , ListenEvent } from '../interfaces' ; import { asyncScheduler , Observable , SchedulerLike } from 'rxjs' ; import { map , share } from 'rxjs/operators' ; interface SnapshotPrevKey < T > { snapshot : DatabaseSnapshot < T > ; prevKey : string | null | undefined ; } param ref param event param listenType param scheduler export function fromRef < T > ( ref , event , listenType = 'on' , scheduler = asyncScheduler ) { return new Observable < SnapshotPrevKey < T > > ( subscriber => { let fn = null ; fn = ref [ listenType ] ( event , ( snapshot , prevKey ) => { scheduler . schedule ( ( ) => { subscriber . next ( { snapshot , prevKey } ) ; } ) ; if ( listenType === 'once' ) { scheduler . schedule ( ( ) => subscriber . complete ( ) ) ; } } , err => { scheduler . schedule ( ( ) => subscriber . error ( err ) ) ; } ) ; if ( listenType === 'on' ) { return { unsubscribe ( ) { if ( fn != null ) { ref . off ( event , fn ) ; } } } ; } else { return { unsubscribe ( ) { } } ; } } ) . pipe ( map ( payload => { const { snapshot , prevKey } = payload ; let key = null ; if ( snapshot . exists ( ) ) { key = snapshot . key ; } return { type : event , payload : snapshot , prevKey , key } ; } ) , share ( ) ) ; }