I have an Angular form array of groups. Elsewhere in the app some subscriptions are setup on formcontrol validation changes. At some point in the life cycle I delete a formgroup. Do I need to be concerned that subscriptions are still open on objects that arent in memory anymore?
-
2Show some code? – maxime1992 May 25 '18 at 14:27
-
1Possible duplicate of [Angular/RxJs When should I unsubscribe from \`Subscription\`](https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription) – Nicolas Gehlert May 25 '18 at 14:40
2 Answers
NO
If you call .subscribe anywhere in your code, the only way to not leak memory is to make sure those subscriptions gets unsubscribed again.
You need to either manually unsubscribe each one or make sure the observables you subscribe to are all finite - meaning they have an "end" signal somewhere. They can be either a limited sequence (.first(), .take(), etc) or they can be toggled off by ending in a .takeWhile() or .takeUntil()
The subscriptions does not care if you leave scope, remove referenced object or even navigate away. You need to make sure they get unsubscribed.
See my answer here: RXJS - Angular - unsubscribe from Subjects

- 15,097
- 21
- 80
- 101
Do I need to be concerned that subscriptions are still open on objects that arent in memory anymore?
As long as the subscription/the observable is open and running the variable will still be in memory even if your parent element is not available anymore. Thus leading to leaking memory.
Golden rule: You should always unsubscribe observables.
There are certain exceptions/edge cases to this rule, for example Http Requests automatically unsubscribe themselves after completing, thus theoretically not needing to unsubscribe.
edit: I found an article that explains it more in depth Angular/RxJs When should I unsubscribe from `Subscription`

- 2,626
- 18
- 39
-
I appreciate your answer immensely and that was a great answer over there but doesn't solve my particular problem. I am setting up subscriptions from within modules. I should have posted code - I will update my question, however for now: I have a separate es6 module with a method that takes 2 form controls and sets up subscriptions to their validation states. If one gets a new value run validation checks on the other. I call the method from a component. Now there is a subscription that my component doesnt directly create so I don't know how to easily hook into on ngdestroy. – Craig May 25 '18 at 18:03
-
@Craig well if they are created internally it is not really your responsibility to check whether they are unsubscribed, but part of the module/lib that creates them. Or maybe I don't fully understand your case – Nicolas Gehlert May 25 '18 at 20:51