javascript - How to stop observers in Observable.merge?
问题描述
I have a method that creates timer:
create(options: any) {
return timer(0, 1000).pipe(
map(() => {
return options;
}),
takeWhile(() => new Date() < options.finishDate)
);
}
Then this timer I add to array this.timers
of Observables:
this.timers.push(this.create({finishDate: new Date()}))
When I merge observers:
this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
console.log(x);
});
I see that console.log(x);
continues work despite timer was finished.
Why? And how to stop all timers in array?
I can unsubscribe here:
Observable.merge(this.timers).subscribe(x => {
x.unsubscribe();
});
But it does not stop Observable.merge
.
解决方案
this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
console.log(x);
});
In this case mergeObserver is not an observable but a subscription. The subscribe method returns a subscription. So renaming this to mergeSubscription and calling unsubscribe on this object is how to unsubscribe.
If you want a reference to the observable you need to subscribe after you have taken a reference.
this.mergeObserver = Observable.merge(this.timers);
this.mergeSubscription = this.mergeObserver.subscribe(x => {
console.log(x);
});
and then you unsubscribe with the mergeSubscription object.
Observable.merge(this.timers).subscribe(x => {
x.unsubscribe();
});
Here you cannot call unsubscribe on x as x is the value that comes out of the merged timers. When one of the timers emits then the merge will emit that value as well, it is just a number and does not have an unsubscribe method.
推荐阅读
- python - 转换为 Python 的异步调用
- reactjs - 从共享同一父域的多个 Web 应用程序注销
- android - 在 RecyclerView 上使用 Glide 缩小图像质量低
- javascript - 这个 Postman Pre-request Script 是如何翻译成 JavaScript 的?
- javascript - 如何从事件监听器的回调函数中返回一个值
- android - 反应原生图像裁剪
- r - 我需要在一组列中找到最大值,然后将每个单独的记录除以该值。有什么帮助吗?使用聚合?
- mysql - 根据每个员工每周/每月的工作天数计算积分
- reactjs - React Context 和 Storybook:在组件故事中更改 React Context 的值
- google-sheets - 为什么在条件格式公式中引用另一个 Google 表格选项卡不起作用?