import { Observable , Subscription } from 'rxjs' ; import { initEvent } from '../../events/lifecycle' ; import { controlledPromise } from '../../helpers/controlledPromise/controlledPromise' ; import { getEventType } from '../../helpers/getEventType/getEventType' ; import { AnyEventCreator , Event } from '../createEvent/createEvent.h' ; import { WaitFor } from './createApp.h' ; const isEvent = ( ev ) : ev is AnyEventCreator | string => { return typeof ev === 'string' || typeof ev === 'function' ; } ; export const getReadyPromise = < State > ( event$ , getState , waitFor ) : Promise < Partial < State > > => { const [ promise , resolve ] = controlledPromise < Partial < State > > ( ) ; const toWait = new Set < string > ( waitFor . reduce ( ( result , event ) => { if ( isEvent ( event ) ) { result . push ( getEventType ( event ) ) ; return result ; } if ( event . condition && ! event . condition ( ) ) { return result ; } const type = getEventType ( event . event ) ; if ( event . timeout ) { setTimeout ( ( ) => { removeEvent ( type ) ; } , event . timeout ) ; } result . push ( type ) ; return result ; } , [ initEvent . getType ( ) ] ) ) ; const removeEvent = ( type ) => { if ( ready ) { return ; } toWait . delete ( type ) ; if ( toWait . size === 0 ) { ready = true ; resolve ( getState ( ) ) ; subscription . unsubscribe ( ) ; } } ; let ready = false ; const subscription = event$ . subscribe ( { next ( event ) { removeEvent ( event . type ) ; } } ) ; return promise ; } ;