import { BehaviorSubject , Observable , Subject } from 'rxjs' ; import { distinctUntilChanged , endWith , map , pairwise , startWith , takeUntil , tap , } from 'rxjs/operators' ; import { FatalErrorsSetup } from '../fatal_errors' ; import { CoreService } from '../../types' ; public export interface LoadingCountSetup { addLoadingCountSource ( countSource$ ) : void ; getLoadingCount$ ( ) : Observable < number > ; } /**
 * See  LoadingCountSetup .
 *  public export type LoadingCountStart = LoadingCountSetup ; internal export class LoadingCountService implements CoreService < LoadingCountSetup , LoadingCountStart > { private readonly stop$ = new Subject ( ) ; private readonly loadingCount$ = new BehaviorSubject ( 0 ) ; public setup ( { fatalErrors } ) { return { getLoadingCount$ : ( ) => this . loadingCount$ . pipe ( distinctUntilChanged ( ) ) , addLoadingCountSource : ( count$ ) => { count$ . pipe ( distinctUntilChanged ( ) , tap ( ( count ) => { if ( count < 0 ) { throw new Error ( 'Observables passed to loadingCount.add() must only emit positive numbers' ) ; } } ) , takeUntil ( this . stop$ ) , endWith ( 0 ) , startWith ( 0 ) , pairwise ( ) , map ( ( [ prev , next ] ) => next - prev ) ) . subscribe ( { next : ( delta ) => { this . loadingCount$ . next ( this . loadingCount$ . getValue ( ) + delta ) ; } , error : ( error ) => fatalErrors . add ( error ) , } ) ; } , } ; } public start ( { fatalErrors } ) { return this . setup ( { fatalErrors } ) ; } public stop ( ) { this . stop$ . next ( ) ; this . loadingCount$ . complete ( ) ; } }