[英]When/how to unsubscribe: Management subscription in RxJS and Angular project
Here's my code snippet(example) 这是我的代码段(示例)
fetchData(): void {
if (this.subscription$) {
this.subscription$.unsubscribe();
}
this.subscription$ = this.store.select('someEvent')
.subscribe(data => {
console.log(data);
});
}
ngOnDestroy() {
this.subscription$.unsubscribe();
}
I need to call the fetchData
method to add another subscription to get the current state from store
. 我需要调用
fetchData
方法来添加另一个订阅,以从store
获取当前状态。 So at this point, I've implemented it like above in order to free up the previous subscription. 因此,在这一点上,我已经像上面一样实现了它,以释放先前的订阅。 It works the way I wanted it to work but I feel like the code is not neat.
它以我想要的方式工作,但是我觉得代码并不整齐。 I was digging into
takeUntil
and takeWhile
to make code more Rx
way but I didn't make it. 我正在研究
takeUntil
和takeWhile
以使代码更像Rx
但是我没有做到。
Use a subject to signal destruction 使用对象破坏信号
destroyed$=new Subject()
fetchData(): void {
this.store.select('someEvent').takeUntil(destroyed$)
.subscribe(data => {
console.log(data);
});
}
ngOnDestroy() {
destroy$.next()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.