Since the ngOnInit is called only once in app's life, when I make a subscription to an observable in ngOnInit, is it still necessary to unsubscribe?
Is it possible for the app to create memory leak for the browser after the app/tab is closed?
Since the ngOnInit is called only once in app's life, when I make a subscription to an observable in ngOnInit, is it still necessary to unsubscribe?
Is it possible for the app to create memory leak for the browser after the app/tab is closed?
The Short answers are:
1) Always
2) Yes
This article describes very well why we should unsubscribe from all observables, and how to do it in an effective way in angular.
If you are Subscribing on the ngOnInit
function you should be unsubscribing via ngOnDestroy
.
I usually create an unsubscribe
Subject, and call next()
on it on ngOnDestroy
. I would have all my subscriptions with a takeUntil(unsubscribe)
.
This is what I mean:
unsubscribe = new Subject();
(...)
subscribeTo() {
this.myService.getAll().pipe(
takeUntil(this.unsubscribe),
).subscribe(data => this.localData = data);
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
My answer is YES.
If this happen only one time in the OnInit
lifecycle then you use take(1)
is enough.
Example:
ngOnInit() {
this.observableData$ = this.myService.getAll().pipe(take(1));
}
The benefits are:
unsubscribe
ngOnDestroy
However, I suggested you another way to handle data by reactive programming in this article. Because subscribe
to get data is not right. We just use subscribe
to do callback for another stuff (not data).
I personally never subscribe an use the async pipe to manage subscriptions for me.
data$ = this.service.getData();
and in the template
<ng-conatainer *ngIf="data$ | async as data">
{{ data | json }}
</ng-conatainer>
No need for any subscriptions.