Hows best to unsubscribe from an observable using a takeUntil.
From what I understand takeUntil automatically does the complete for you.
Below is how I normally do a unsubscribe from an observable. But not sure if done correctly. Do I really need the "this.destroyed$.complete();" if takeUntil does the complete for me?
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?
Personally I prefer this solution, have another subject just to handle unsubscribe and mix up with takeUntil probably make things too complex
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()})
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.