To avoid Observable memory leaks inside Components, I am using takeUntil() operator before subscribing to Observable.
I write something like this inside
You only need to unsubscribe like:
subscr: Subscription;
ngOnInit() {
this.subscr = this.http
.get('test')
.pipe(takeUntil(this.unsubscribe$))
.subscribe(x => console.log(x));
}
ngOnDestroy() {
this.subscr.unsubscribe();
}
To unsubscribe using takeUntil():
The solution is to compose our subscriptions with the takeUntil operator and use a subject that emits a truthy value in the ngOnDestroy:
export class AppComponent implements OnInit, OnDestroy {
destroy$: Subject = new Subject();
ngOnInit() {
this.http
.get('test')
.pipe(takeUntil(this.unsubscribe$))
.subscribe(x => console.log(x));
}
ngOnDestroy() {
this.destroy$.next(true);
}
}
Note that using an operator like takeUntil instead of manually unsubscribing will also complete the observable, triggering any completion event on the observable.
See here