Angular: how to unsubscribe all observables in one line

If you have put your hands on Angular, then you most probably have used Observables. Aren’t they cool! They make angular components reactive and make developer life stress free (or at least reduce some of it 😉 )

You started using Observables and thought what could go wrong. Until one day you realize your application performance is going down and you have no clue. Perhaps you forgot to destroy one Observable subscription which has caused a memory leak. That mortal subscription is holding onto your component and not letting angular kill it even though you don’t need it.

Over time as your application size increases, so does the number of Observables and obviously the number of subscriptions. It is not hard to miss a subscription here or there. But thanks to our dev community we have already found cool pattern that lets the management of subscription inside angular components more declarative. Therefore as you start following the declarative pattern, you will naturally avoid the memory leaks caused by Observables. Enough talking lets get to the bussiness.

Lets say that inside your component you have these two observables.

export class AppComponent implements OnInit, OnDestroy {
  ob1$ = of(1);
  ob2$ = of(2);
...

Now you will create a Rxjs Subject stream, the lifetime of which will be the same as that of the component in context (how? we will see in a moment).

export class AppComponent implements OnInit, OnDestroy {
  ob1$ = of(1);
  ob2$ = of(2);

  onDestroy$ = new Subject<void>();
...
[amazon_auto_links id=”529″]

When you subscribe to the Observables, you will right away set the lifetime of the Observables, thanks to the takeUntil Rxjs operator. The lifetime of the Observables will be set to the lifetime of the Subject stream.

...
ngOnInit() {
    this.ob1$.pipe(
      takeUntil(this.onDestroy$)
    )
      .subscribe(val => console.log(val));

    this.ob2$.pipe(
      takeUntil(this.onDestroy$)
    )
      .subscribe(val => console.log(val));
  }
...

And then later when the component is about to be destroyed, you will finish the stream. This will destroy all the Observables in your component right away (in just 2 lines).

...
ngOnDestroy() {
  this.onDestroy$.next();
  this.onDestroy$.complete();
}

How cool is that. Yes thats it! No need to remember which subscription has been destroyed and if you have missed any or not. And this keeps the component code clean and readable.

Leave a Reply