简体   繁体   中英

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM