Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active May 17, 2019 14:31
Show Gist options
  • Save hollygood/d39cdd70e49b3b99ef8b149a18567f3d to your computer and use it in GitHub Desktop.
Save hollygood/d39cdd70e49b3b99ef8b149a18567f3d to your computer and use it in GitHub Desktop.
Different ways to unsubscribe Angular 6 Observables

Use 'unsubscribe':

export class ExampleComponent implements OnInit, OnDestroy {
  exampleSubOne: Subscription;
  exampleSubTwo: Subscription;

  constructor(private exampleService: ExampleService) {}

  ngOnInit() {
    this.exampleSubOne = this.exampleService.someFunction()
      .subscribe(() => {
          //do something
      })

    this.exampleSubTwo = this.exampleService.someOtherFunction()
      .subscribe(() => {
          //do something
      })
  }

  ngOnDestroy(): void {
        this.exampleSubOne.unsubscribe();
        this.exampleSubTwo.unsubscribe();
    }
  }
}

Use 'takeUntil'

export class ExampleComponent implements OnInit, OnDestroy {

  private unsubscribe$ = new Subject();

  constructor(private exampleService: ExampleService) {}

  ngOnInit() {
    this.exampleSubOne = this.exampleService.someFunction()
      .pipe(takeUntil(unsubscribe$))
      .subscribe(() => {
          //do something
       });

    this.exampleSubTwo = this.exampleService.someOtherFunction()
      .pipe(takeUntil(unsubscribe$))
      .subscribe(() => {
          //do something
      });
  }

  ngOnDestroy(): void {
      this.unsubscribe$.next();
      this.unsubscribe$.unsubscribe();
    }
  }
}

Use 'async pipe'

export class AsyncPipeExampleComponent implements OnInit {
  exampleSubscription: Observable;
  constructor(private exampleService: ExampleService) {}

  ngOnInit() {
      this.exampleSubscription = this.exampleService.getMessage();
    }
  }
}

// in html
{{ exampleSubscription | async }}

Other Examples

/**
* use unsubscribe() for setInterval()
*/
function subscribe(observer) {
  var intervalID = setInterval(() => {
    observer.next('hi');
  }, 1000);

  return function unsubscribe() {
    clearInterval(intervalID);
  };
}

var unsubscribe = subscribe({next: (x) => console.log(x)});

// Later:
unsubscribe(); // dispose the resources

Storing Subscriptions in an Array

let subs: Subscription[] = [];

ngOnInit() {
  this.subs.push(this.service.Subject1.subscribe(() => {}));
  this.subs.push(this.service.Subject2.subscribe(() => {}));
  this.subs.push(this.service.Subject3.subscribe(() => {}));
}

ngOnDestroy() {
  subs.forEach(sub => sub.unsubscribe());
}

//===== or use Subscription.add

let subs: Subscription[] = [];

ngOnInit() {
  this.subs.push(this.service.Subject1.subscribe(() => {}));
  this.subs.push(this.service.Subject2.subscribe(() => {}));
  this.subs.push(this.service.Subject3.subscribe(() => {}));
}

ngOnDestroy() {
  subs.forEach(sub => sub.unsubscribe());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment