Angular RxJS Subscription

Photo by ROMAN ODINTSOV from Pexels

Overview

There are a multiple ways to unsubscribe from an observable. As of the time this post was written, the most common was is using the Subscription() feature. You just instantiate Subscription() once and add all the observables into a single variable.

Declare a new subscription in a component as follows:

subs = new Subscription();

That is basically all you need to do call add Subscription. Now to see it in action.

   this.subs.add(this.auth.getSomething(this.form.get('field').value)
    .subscribe((data) => {
      console.log('Status: ' + data.status);
      console.log('Message: ' + data.msg);
      console.log('Data: ' + data.data);
    },
    (err: HttpErrorResponse) => {
      console.log(err);
    }));
   this.subs.add(this.auth.getSomethingElse(this.form.get('field').value)
    .subscribe((data) => {
      console.log('Status: ' + data.status);
      console.log('Message: ' + data.msg);
      console.log('Data: ' + data.data);
    },
    (err: HttpErrorResponse) => {
      console.log(err);
    }));

From your ngOnDestroy() function.

  ngOnDestroy(): void {
    this.subs.unsubscribe();
  }

That’s it. Goodbye memory leaks.