9

I am wondering If I subscribe to stream in my constructor like this:

_eventEmitterService.event.subscribe((msg)=>{})

So when I change the view to different component, and come back, the events are triggered twice from that stream. Do I need to unsubscribe each time I change the component, by using ngOnDestroy?

Thanks

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
uksz
  • 18,239
  • 30
  • 94
  • 161

2 Answers2

13

I found it! And yes, per documentation as stated in the angular2 lifecycle-hook guide:

ngOnDestroy
Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.

So yes, you need to unsubscribe from observables on ngOnDestroy()

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
5

Just an additional hint to the Pierre's great answer. The async pipe automatically unsubscribes observables it's applied on. So you need to unsubscribe for observables you manage by your own.

See this line in source code:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Github link is dead now. Could you expand a little bit more, your answer seems to contradict Pierre a bit, so I'm unsure when I need to manually cleanup? Angular official tutorial doesn't do any cleanups as far as I can see. – Davor Jun 29 '17 at 08:40