Search code examples
javascriptrxjsrxjs6

RxJS Error Observable when another emits value


Contrived example of what I'm trying to do here:

const source = interval(1000);
const errorWhenThisEmits = timer(2500);

source.pipe(/* someOperatorHere? */).subscribe({
  next: () => console.log('next!'),
  error: (err) => console.log(err)
});

// desired outcome:
// 1000ms: next!
// 2000ms: next!
// 2500ms: error message

Is it possible to cause the source observable to error when the second observable emits a value?

takeUntil gets close, but completes instead of errors.


Solution

  • You could merge the observables

    const source = interval(1000);
    const notifier = timer(2500).pipe(switchMap(() => throwError("error message")));
    
    merge(source, notifier).subscribe({
      next: () => console.log("next!"),
      error: err => console.log(err)
    });
    

    See stackblitz: https://stackblitz.com/edit/rxjs-ony9vx?file=index.ts