Michael
Michael

Reputation: 829

How to unsubscribe from Observable if there is no object of type "Subscription"?

If I subscribe to an Observable, how can I unsubscribe from it, if there is no object of type "Subscription"?

If I have something like:

this.subscription = bla ... 

then I can unsubscribe from it as follows (in the ngOnDestroy()-method):

this.subscription.unsubscribe();

But what if I have something like this:

 ngOnInit() {

    this.isLoggedIn$ = this.authService.isLoggedIn();

    this.isLoggedIn$.subscribe(res => {
      if (res) {
        this.isLoggedIn = true;
      } 
      else {
        this.isLoggedIn = false;
      }
    });

  }

How can I unsubscribe from this? Do I even have to unsubscribe? If not, why not?

Upvotes: 0

Views: 661

Answers (3)

Danish Arora
Danish Arora

Reputation: 338

There are 3 methods to unsubscribe an observable

  1. You can use above approach as this.subscription to assign subscribe for every subscribe and then unsubscribe each every explicitly. (It should be avoided)

  2. You can use takWhile pipe by using the example below:

    private isAlive = true;
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
    
      this.subscription = this.isLoggedIn$
       .pipe(takeWhile(() => this.alive))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    
    }
    
    
    ngOnDestroy() {
       console.log('[takeWhile] ngOnDestory');
       this.alive = false;
    }
    
  3. Use takeUntil operator:

    private unsubscribe: Subject<void> = new Subject();
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
    
      this.subscription = this.isLoggedIn$
       .pipe(takeUntil(this.unsubscribe))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    }
    
    ngOnDestroy() {
      this.unsubscribe.next();
      this.unsubscribe.complete();
    }
    

I Hope This helped!!

Upvotes: 3

Vugar Abdullayev
Vugar Abdullayev

Reputation: 2085

Just check if this.isLoggedIn$ exists before unsubscribe

ngOnDestroy() {
this.isLoggedIn$ && this.isLoggedIn$.unsubscribe();
}

Upvotes: 1

Ian MacDonald
Ian MacDonald

Reputation: 14020

You have actually provided your own answer here: bla ... is your this.isLoggedIn$.subscribe( ... ) call.

ngOnInit() {

  this.isLoggedIn$ = this.authService.isLoggedIn();

  this.subscription = this.isLoggedIn$.subscribe(res => {
    if (res) {
      this.isLoggedIn = true;
    } 
    else {
      this.isLoggedIn = false;
    }
  });

}

Upvotes: 2

Related Questions