Tuesday, November 28, 2017

Angular: Unsubscribe observables

When you subscribe to an observable in Angular, a subscription is created. To avoid memory leaks in your Angular components it is important that you unsubscribe from any subscription in the OnDestroy lifecycle hook.

Although you could think this is a good general rule, there are a lot of exceptions where Angular does the right thing and handles the unsubscribe for you:

  • AsyncPipe: if you are using observable streams via the AsyncPipe then you do not need to worry about unsubscribing. The async pipe will take care of subscribing and unsubscribing for you.
  • Router observables: The Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don't need to unsubscribe from the route params Observable.
  • Http observables: Http observables produces finite values and don’t require an unsubscribe.

As a general conclusion, in most cases you don’t need to explicitly call the unsubscribe method. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published.

1 comment:

Devikala said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic.
Ultrasonic Testing Courses in Chennai