unsubscribing – the right way

export class MyComponent implements OnDestroy, OnInit {

  public user: User;
  private alive: boolean = true;

  public ngOnInit() {
    this.userService.authenticate(email, password)
      .takeWhile(() => this.alive)
      .subscribe(user => {
        this.user = user;
      });
  }

  public ngOnDestroy() {
    this.alive = false;
  }

}

 

you can subscribe to multiple observable, and with one statement in the ngOnDestroy event, unsubscribe from them all.

Using this way, the observable’s complete event will fire, in case you handle it.

further reading, by Ben Lesh: RxJS: Don’t Unsubscribe

 

Advertisements