rxjsrxjs6

How to delay throwError with RxJS?


As expected, the following code emits 42 after 5 seconds:

const valueObservable = of(42).pipe(delay(5000));
valueObservable.subscribe((value) => console.log(value));

However, this throwing version errors immediately on subscription:

const throwingObservable = throwError(new Error('My Error')).pipe(delay(5000));
throwingObservable.subscribe((value) => console.log(value), (error) => console.error(error));

Why does this happen? How do I delay the throwing of the error?


Solution

  • Rxjs error is exception, it stop immediately the stream and let you catch it to react to something un expected. I guess you have no way to manipulate throwError stream except with catchError

    Solution 1: Manipulate stream before throw the error.

    const throwingObservable = throwError(new Error('My Error'));
    timer(5000).pipe(mergeMap(e => throwingObservable))
      .subscribe((value) => console.log(value), (error) => console.error(error));
    

    Solution 2: Catch the error, delay the stream, then dispatch it again

    throwingObservable.pipe(
      // We catch the error, we delay by adding timer stream, then we mergeMap to the error.
      catchError(e => timer(1000).pipe(mergeMap(t => throwError(e)))
    )).subscribe(console.log, console.error);
    

    You can see it in action