首页 > 解决方案 > 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?

标签: angularmemory-leaksrxjsobservableangular-reactive-forms

解决方案


好的,所以我在 Chrome Dev Tools 中使用 Memory Profiler 进行了一些实验。我发现,无论您是取消订阅FormControl#valueChanges还是组件被破坏,结果几乎都是一样的。在这两种情况下,SubjectSubscription都会收集垃圾。看看下面的结果。


当组件被销毁时

组件被销毁时一些已删除对象的列表

手动退订时

取消订阅 Observable 时一些已删除对象的列表

所以我认为可以肯定地说订阅确实被删除了,不需要手动取消订阅。


推荐阅读