RxJS Error Observable when another emits value

561 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

Discovered takeUntil will error the parent observable if the notifier observable errors.

const source = interval(1000);
// added switchMap to throwError
const notifier = timer(2500).pipe(switchMap(() => throwError('error!')));

source.pipe(takeUntil(notifier)).subscribe({
  next: (data) => console.log(data),
  error: (err) => console.log(err)
});

This outputs:

0
1
error!