I'm trying to figure out why all of the Angular apps I look at assign subscriptions to a variable, only to have to unsubscribe via ngOnDestroy(). For example:
export class ViewBookPageComponent implements OnDestroy {
actionsSubscription: Subscription;
constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
this.actionsSubscription = route.params
.select<string>('id')
.map(id => new book.SelectAction(id))
.subscribe(store);
}
ngOnDestroy() {
this.actionsSubscription.unsubscribe();
}
}
What happens if I just remove actionsSubscription altogether? Will a subscription still be created but not destroyed? In the below case, you still get the side-effect, but don't have to bother unsubscribing. So is actionsSubscription necessary for garbage collection?
export class ViewBookPageComponent {
constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
route.params
.select<string>('id')
.map(id => new book.SelectAction(id))
.subscribe(store);
}
}
You are right, if you remove actionsSubscription
altogether, the subscription
will still be created but you won't be able to unsubscribe
from it via ngOnDestroy
, after you leave the component. If not unsubscribed, the observable
might still keep streaming data, even after moving away from the component, hence causing memory leaks. So, assigning an observable subscription to a variable and forcing unsubscribe
ensures that the data stream from that observable is stopped when component is destroyed.
I learned more about unsubscribe
from this article by Brian Love.
One important thing I noted from it -
if you are using observable streams via the
AsyncPipe
then you do not need to worry about unsubscribing. The async pipe will take care of subscribing and unsubscribing for you.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With