Search code examples
angularrxjsobservableserver-sent-events

RxJS Observable - return if first event not emitted in first x mins, otherwise continue for x+y mins


RxJS/Angular experts, need your input/pointers

I am trying to put a logic on the Observable (created from http call)

I want to return (come out of the waiting and discontinue subscription on the observable) if first event is not emitted from Observable in first 3 mins

But if first event is emitted in first 3 mins, I want to continue with subscription & get the data for total of 10 mins (from the time subscription started)

As of now, using takeUntil(timer(1000 * 60 * 10) to wait for total 10 mins, but want to divide this wait in 3 mins, and if some response -> then only extend by 7mins

pseudo code

Observable
.pipe(
    takeUntil(timer(10* 60 * 1000)),
    map (res => {}),
    filter()
)
.subscribe(

)

Note: the above call wraps on the EventSource SSE call

I thought to use out of box RxJS timeout, but does not fit to my requirement


Solution

  • A working stackblitz example

    Use race operator for the first x mins condition, takeUntil is passed into http request for the second condition :

     fistTimerBenchMark$ = timer(3000).pipe(switchMap(x => throwError('ended before 3s')));
    
     //Mock http request
     mockHttp$ = timer(2000,2000).pipe(map(x => 'http respones'),takeUntil(timer(10000)));
    
     ngOnInit(){
          race(this.fistTimerBenchMark, this.mockHttp$)
          .subscribe( x => console.log(x),  err => console.log(err))
     }
    

    Additionaly, I used throwError to complete the observable for the first x min condition, since unsubscribe it in an observable's pipeline or subscriber is not a good convention.