Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Aren't FormControl#valueChanges' Subscriptions Garbage Collected?

I have gone through plenty of threads saying that one needs to unsubscribe from FormControl#valueChanges to prevent memory leaks. I understood the "when" and "how" to unsubscribe from Observables. As I understand, Observables that produce infinite number of values need to be unsubscribed and FormControl#valueChanges is one such Observable.

But my question is, why aren't these Observabless garbage collected? I mean when an Angular component gets destroyed, the references are dead right? The form control in the template is no longer there. The FormControl instance is also gone. So if the "source" of the Observable, the FormControl, is gone then how come its member valueChanges still exist and retain its subscriptions?

like image 306
Tuhin Karmakar Avatar asked Nov 17 '22 05:11

Tuhin Karmakar


1 Answers

Okay so I performed some experiments with the Memory Profiler in Chrome Dev Tools. What I found was, whether you unsubscribe from FormControl#valueChanges or the component gets destroyed the result is almost the same. In both cases one SubjectSubscription gets garbage collected. Take a look at the results below.


When component gets destroyed

List of some deleted objects when component got destroyed

When manually unsubscribed

List of some deleted objects when Observable was unsubscribed

So I think it's safe to say that the subscriptions do in fact get removed and one does not need to unsubscribe manually.

like image 126
Tuhin Karmakar Avatar answered Dec 05 '22 16:12

Tuhin Karmakar