1
votes

What happen when you subscribe to observable, then the source of this observable is no longer used in application? Is there any memory leak? I have FormArray which have some of FormGroup. I subscribe for every of FormGroup.valueChanges, and do I need tu unsubscribe when FormGroup is removed from FormArray? Same goes to Subjects, do i need to unsubscribe to them if for some reason I would have Subject in for example Component and this component will be destroyed? I've read this answer Angular/RxJs When should I unsubscribe from `Subscription` but there is nothing about my case.

1
For me, I unsubscribe always to be extra safe. To "finish" a subject, call .complete() on it.AliF50

1 Answers

0
votes

I'd say there is no need to unsubscribe. It won't do any harm if you do, but I don't think it's necessary.

You can find a more detailed explanation in this answer.

But the gist is this: in this case, the memory leaks occur when the subscriber created from the subscribes' callback is still part of the Subject's subscribers list. This means that when the component will be created again, another subscriber of that type will be added to the list, while the old one is still there. That's why the memory leak occurs.

However, if you unsubscribe, that subscriber won't be part of that subscribers list anymore. The reason I'd say there is no need to unsubscribe in this case it because the only thing that would still reference that subscriber, the Subject instance, which is what prevents that old subscriber from being garbage collected, will be nulled out. My reasoning is: if what keeps that subscriber alive is nulled out, then there is no way that subscriber's next callback can be reached again, so it can be garbage collected.