It's surprisingly hard to get a straight answer on if and when you should unsubscribe from an Angular Observable.
I have the following scenario:
this.subscription = this.service.makeHTTPCall(stuff).subscribe(x => {
//do something
});
There are a few solutions I see:
Don't store the subscription as a variable, does this mean I don't have to unsubscribe?
this.service.makeHTTPCall(stuff).subscribe(x => { //do something });
Store the subscription as a variable and unsubscribe in ngOnDestroy
ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } }
Do nothing, Angular sorts all of the unsubscribe stuff out for you
I know there are third party libraries like ng-take-until-destroy
, but assuming we don't have any third party libraries which is the advised method for unsubscribing?
takeUntilDestroyed
from Angular angular.dev/api/core/rxjs-interop/takeUntilDestroyed – Cent