I have a component containing a Subject
which is only being used within that same component (subscribe
is called by ngOnInit
, next
is called in the template) would it lead to memory leak when left subscribed?
Asked
Active
Viewed 75 times
0

Rafi Henig
- 5,950
- 2
- 16
- 36
-
Even if you could leave it subscribed, why not just unsubscribe in `ngOnDestroy`? – Heretic Monkey Sep 06 '20 at 01:00
-
`@Heretic Monkey` why unsubscribe if it's not necessary – Rafi Henig Sep 06 '20 at 01:05
-
1Safety. So, right now, the component's `Subject` is not being used elsewhere. Next year, someone comes along and subscribes to it. Now you've got a memory leak you could have easily bypassed by simply unsubscribing in the first place. Up to you, of course, you know the risks better than I... – Heretic Monkey Sep 06 '20 at 01:10
-
The best practice would be to complete the subject in the ngOnDestroy rather than manage any subscriptions. – Adrian Brand Sep 06 '20 at 02:27
-
See this: https://stackoverflow.com/a/57009988/8578281 – Goga Koreli Sep 20 '20 at 14:00
1 Answers
1
If the observable is created in the component they both fall into garbage collection at the same time. A leak only occurs if the component is subscribed to an observable that lives in another spot such as a service and has not fallen into garbage collection.

Adrian Brand
- 20,384
- 4
- 39
- 60