[英]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?当第二个 observable 发出一个值时,是否有可能导致源 observable 出错?
takeUntil
gets close, but completes instead of errors. takeUntil
接近,但完成而不是错误。
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参见stackblitz: https://stackblitz.com/edit/rxjs-ony9vx?file=index.ts
Discovered takeUntil
will error the parent observable if the notifier observable errors.如果通知器 observable 出错,发现takeUntil
将出错父 observable。
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.