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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s