[英]Hows best to unsubscribe from an observable using a takeUntil in Angular2
Hows best to unsubscribe from an observable using a takeUntil.如何最好地使用 takeUntil 取消订阅 observable。
From what I understand takeUntil automatically does the complete for you.据我所知,takeUntil 会自动为您完成。
Below is how I normally do a unsubscribe from an observable.以下是我通常如何取消订阅 observable。 But not sure if done correctly.
但不确定是否正确完成。 Do I really need the "this.destroyed$.complete();"
我真的需要“this.destroyed$.complete();”吗? if takeUntil does the complete for me?
如果 takeUntil 对我来说完成了吗?
This is my current attempt that works but unsure if best method:这是我目前的尝试,但不确定是否是最佳方法:
private destroyed$: Subject<void> = new Subject();
ngOnIt(): void {
this.serviceA.getData
.takeUntil(this.$destroyed)
.subscribe(val => {
console.log('Current value:', val);
});
};
ngOnDestroy(): void {
this.destroyed$.next();
this.destroyed$.complete();
};
I was thinking of removing the .complete in the ngOnDestory but not sure if that would cause memory leaks?我正在考虑删除 ngOnDestory 中的 .complete 但不确定这是否会导致内存泄漏?
Personally I prefer this solution, have another subject just to handle unsubscribe and mix up with takeUntil probably make things too complex我个人更喜欢这个解决方案,有另一个主题只是为了处理取消订阅并与 takeUntil 混淆可能会使事情变得太复杂
private _subscriptions:Subscription[];
ngOnIt(): void {
this._subscriptions.push(this.serviceA.getData
.subscribe(val => {
console.log('Current value:', val);
})
)
};
ngOnDestroy(): void {
this._subscriptions.foreach(subs=>{ subs.unsubscribe()})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.