Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe each time onDestroy in component?

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

like image 945
uksz Avatar asked Apr 22 '16 13:04

uksz


2 Answers

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()

like image 176
Poul Kruijt Avatar answered Oct 15 '22 17:10

Poul Kruijt


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:

  • https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/async_pipe.ts#L74
like image 30
Thierry Templier Avatar answered Oct 15 '22 17:10

Thierry Templier