Search code examples
javascriptangularobservablesubscription

What is the difference between subscription.unsubscribe() and subscription.remove()?


I am using Angular 5 and have subscribed an observable using the subscribe() method. I want to know if only calling the unsubscribe() method on the subscription will be sufficient to cleanup everything, or should I also call remove() method?

code snippet:

`

// somewhere in a method
this.s1 = someObservable.subscribe((value) => {
     //somecode
 });
// in ngOnDestroy
this.s1.unsubscribe(); // should I also call .remove()

`


Solution

  • .remove remove the subscription from an internal list, but it does not unsubscribe.

    .unsubscribe clean up everything, do the unsubscribe and remove the observer from the internal list. (There was a bug (fixed) that didn't remove the observer from the list)

    .takeWhile keep alive the subscription whilst a certain situation continues to be false

    example:

    this.service.method()
    .subscribe(res => {
      //logic
    });
    

    this will never unsubscribe.

    this.service.method()
        takeWhile(() => this.isAlive) // <-- custom variable setted to true
        .subscribe(res => {
          //logic
        });
    
    ngOnDestroy(){
        this.isAlive = false;
    }
    

    Automatic unsubscribe when the component is going to be destroyed.

       this.s1 = someObservable.subscribe((value) => {
            //somecode
        });
    
    public yourMethod(){
        this.s1.unsubscribe();
    }
    

    this subscription will exists and be "alive" until yourFunction is not called.

    --

    I personally like to use the rxjs operator takeWhile to keep the code clean. In a very big project or single component having multiple subscription it's confusing having (IE) 30 variables: Subscription. So If you are asking when to use the takeWhile operator my answer is: (Taking as example one subscription) -> If you are sure that the unsubscribe needs to be done when the component is destroyed, use takeWhile. If you need to unsubscribe in a certain scenario where the component is still "alive", use the second example I wrote.

    Hope to have clarified the argument.