admin管理员组

文章数量:1287505

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()

`

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()

`

Share Improve this question edited Nov 22, 2018 at 10:20 B001ᛦ 2,0596 gold badges25 silver badges32 bronze badges asked Nov 22, 2018 at 10:13 Akhilesh ShuklaAkhilesh Shukla 3113 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

.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 ponent 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 ponent 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 ponent is destroyed, use takeWhile. If you need to unsubscribe in a certain scenario where the ponent is still "alive", use the second example I wrote.

Hope to have clarified the argument.

本文标签: javascriptWhat is the difference between subscriptionunsubscribe() and subscriptionremove()Stack Overflow