Search code examples
angulartypescriptobservablesubscription

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?


Solution

  • 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!!