0
votes

In several of the tutorials and documentation I've read about Angular observables, I've seen a lot of warnings on how failing to unsubscribe from a subscription can create memory leak (unless using the async pipe in the component's template).

I have some support classes in my app where I create custom observables, but I was wondering if its important to unsubscribe to them if both the observable and all the subscribers go out of scope. For example, I have a parent class which contains a map of child objects in an array. The parent subscribes to an observable for each of its children to detect changes in the "value" property, and the parent recalculates it's 'total' property whenever the child changes its value.

Then say the parent object goes out of scope, and typically the parent and all the children would be garbage collected so long as no live references to any of the children are hanging around. Is it necessary to for the parent to unsubscribe to each of childchange subscriptions in order for the subscription to be release? Or does the subscription itself get garbage collected when either the subsscribers or the observed object go out of scope? Or will the active subscription itself keep the parent alive, and thus all the children alive?

2

2 Answers

0
votes

As soon as the source Observable is being garbage collected, all of the subscriptions callbacks are collected too, and all of the object referenced by the callbacks so there is no real risk. All of Angular's Observables have they own lifecycle and are destroyed when not needed anymore (HttpClient, route params, guards, resolvers, etc...) so there is no need to worry about unsubscribe when you subscribe to an Angular's Observable.

The dangerous Observables are those you create and for which you don't manage the lifecycle correctly, those can live forever, and can have references to callbacks which have references to objects (like components). Here you can find more information on how memory leaks can happen: Do I need to unsubscribe from an Observable if the Observable is finished with?

0
votes

Yes, your gonna need to unsubscribe the value changes. In angular the HttpModule is the only one you dont have to unsubscribe since its unsubscribe after the http request is done(in the httpModule)