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 badges1 Answer
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.
版权声明:本文标题:javascript - What is the difference between subscription.unsubscribe() and subscription.remove()? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741313195a2371766.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论