Preventing Angular observable leaks

A common Angular beginner error is forgetting to unsubscribe from observables. This leak may not be noticeable at first, but will eventually lead to a sluggish application, or other unexpected behaviours.

One can manually keep track of all subscriptions, in order to properly unsubscribe in ngOnDestroy. However, this is tedious, and error prone.

Depending on your subscription context, there are two solutions that you may like.

For a subscription which is a one shot, you need to retrieve your data, and then fortget it, the RxJS first operator combined if straightforward.

myObservable.pipe(first()).subscribe(...);

If you’re expecting several events, and need to unsubscribe only when the component gets destroyed, then @ngneat/until-destroy, is “a neat way to unsubscribe from observables when the component destroyed

The @UntilDestroy({ arrayName: ‘subscriptions’ }) is a nice way to both explicit the requirement for observables to be unsubsribeds, while minimizing boilerplate code.

Leave a Reply

Your email address will not be published. Required fields are marked *