RxJS keeping a source Observable alive if a switchMapped Observable emits an error

55 views Asked by At

In the following example, the interval Observable will stop emitting values after the first throwError emits.

const { interval, throwError, of } = Rx;
const { take, switchMap, catchError } = RxOperators;

interval(1000).pipe(
  switchMap(() => throwError('error')),
  catchError(() => of(null)),
  take(4)
)

However in the following example, the interval Observable will stay alive and emit 4 times on to the throwError Observable.

const { interval, throwError, of } = Rx;
const { take, switchMap, catchError } = RxOperators;

interval(1000).pipe(
  switchMap(() => throwError('error').pipe(catchError(() => of(null)))),
  take(4)
)

I have a situation where I need the behaviour in the second example where the main Observable stays alive even if the Observable that is switchMapped on to emits an error.

My understanding is that embedding pipes within pipes is bad practice due to the complexity it can add to understanding what the code is doing. Is there a nicer way to achieve the behaviour from the second example?

0

There are 0 answers