import { Query } from '../query-tree/query' ; import { ResultTreeHandler } from '../result-tree/result-tree-handler' ; import { ResultTree } from '../result-tree/result-tree' ; export interface IResultHandler { flush ( ) : void ; getResultHandler ( ) : ResultTreeHandler ; } export class RunningQuery { private handlers : IResultHandler [ ] = [ ] ; private rootRtHandlers : ResultTreeHandler [ ] = [ ] ; constructor ( private query , private resultTree , private disposeCb ) { if ( ! this . disposeCb ) { this . disposeCb = ( ( ) => { } ) . bind ( this ) ; } } public getQuery ( ) { return this . query ; } public attachHandler ( handler ) { if ( ! this . disposeCb ) { throw new Error ( 'cannot attach handler to disposed query' ) ; } for ( let hh of this . handlers ) { if ( hh === handler ) { return ; } } let rhandler = handler . getResultHandler ( ) ; this . handlers . push ( handler ) ; this . rootRtHandlers . push ( rhandler ) ; this . resultTree . addResultHandler ( rhandler , handler . flush . bind ( handler ) ) ; } public detachHandler ( handler ) { for ( let i = 0 ; i < this . handlers . length ; i ++ ) { if ( this . handlers [ i ] === handler ) { this . resultTree . removeResultHandler ( this . rootRtHandlers [ i ] ) ; this . handlers . splice ( i , 1 ) ; this . rootRtHandlers . splice ( i , 1 ) ; break ; } } } public dispose ( ) { if ( ! this . disposeCb ) { return ; } for ( let i = 0 ; i < this . handlers . length ; i ++ ) { this . resultTree . removeResultHandler ( this . rootRtHandlers [ i ] ) ; } this . handlers . length = 0 ; this . rootRtHandlers . length = 0 ; this . disposeCb ( ) ; this . disposeCb = null ; } }