[英]RXJS: How to use takeUntil until another Observable completes (and not emits)
I have two Observables:我有两个 Observable:
1: counts up a value and completes. 1:计数值完成。 (important: May complete before ever emitting any value!)
(重要:可能在发出任何值之前完成!)
2: does stuff until 1 COMPLETES (not emits) 2:做东西直到 1 完成(不发射)
How would you implement this in RxJS?您将如何在 RxJS 中实现这一点?
My first try is using last() like:我的第一次尝试是使用 last() ,例如:
firstObservable.pipe(
takeUntil(secondObservable.pipe(last()))
).subscribe(count =>{
//do stuff with count
});
But the prroblem arises when firstObservable completes without ever emitting any value.但是当 firstObservable 在没有发出任何值的情况下完成时,问题就出现了。 An error is raised:
引发错误:
Error: no elements in sequence
Question : How can i use takeUntil (or any other operator) to stop the subscription after observable 2 completed and not throw an error when no last value ever was emitted?问题:如何在 observable 2 完成后使用 takeUntil (或任何其他运算符)停止订阅,并且在没有发出最后一个值时不抛出错误?
You can use finalize on the secondOvservable
and complete the firstObservable
there.您可以在
secondOvservable
上使用 finalize 并在那里完成firstObservable
。 That way it does not depends on any value emitted, just on the complete event.这样它不依赖于任何发出的值,只依赖于完整的事件。
secondOvservable.pipe(
finalize(() => firstObservable.complete())
).subscribe(count =>{
//do stuff with count
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.