subscription.unsubscribe() 和 subscription.remove() 有什么区别?
What is the difference between subscription.unsubscribe() and subscription.remove()?
我正在使用 Angular 5 并使用 subscribe()
方法订阅了一个可观察对象。我想知道仅在订阅上调用 unsubscribe()
方法是否足以清理所有内容,还是我也应该调用 remove()
方法?
代码片段:
`
// somewhere in a method
this.s1 = someObservable.subscribe((value) => {
//somecode
});
// in ngOnDestroy
this.s1.unsubscribe(); // should I also call .remove()
`
.remove
从内部列表中删除订阅,但它不会 取消订阅。
.unsubscribe
清理一切,取消订阅并从内部列表中删除观察者。 (有一个错误(已修复)没有将观察者从列表中删除)
.takeWhile
保持订阅,因为某种情况是 false
示例:
this.service.method()
.subscribe(res => {
//logic
});
这永远不会退订。
this.service.method()
takeWhile(() => this.isAlive) // <-- custom variable setted to true
.subscribe(res => {
//logic
});
ngOnDestroy(){
this.isAlive = false;
}
组件销毁时自动退订
this.s1 = someObservable.subscribe((value) => {
//somecode
});
public yourMethod(){
this.s1.unsubscribe();
}
此订阅将存在并“有效”,直到 yourFunction
未被调用。
--
我个人喜欢使用 rxjs 运算符 takeWhile
来保持代码整洁。在一个非常大的项目或具有多个订阅的单个组件中,(IE) 30 variables: Subscription
令人困惑。因此,如果您询问何时使用 takeWhile
运算符,我的回答是:(以一个订阅为例)-> 如果您确定 unsubscribe
需要在组件被销毁时完成,请使用花点时间。如果在某个组件还“活着”的场景下需要退订,使用我写的第二个例子。
希望已经澄清了争论。
我正在使用 Angular 5 并使用 subscribe()
方法订阅了一个可观察对象。我想知道仅在订阅上调用 unsubscribe()
方法是否足以清理所有内容,还是我也应该调用 remove()
方法?
代码片段:
`
// somewhere in a method
this.s1 = someObservable.subscribe((value) => {
//somecode
});
// in ngOnDestroy
this.s1.unsubscribe(); // should I also call .remove()
`
.remove
从内部列表中删除订阅,但它不会 取消订阅。
.unsubscribe
清理一切,取消订阅并从内部列表中删除观察者。 (有一个错误(已修复)没有将观察者从列表中删除)
.takeWhile
保持订阅,因为某种情况是 false
示例:
this.service.method()
.subscribe(res => {
//logic
});
这永远不会退订。
this.service.method()
takeWhile(() => this.isAlive) // <-- custom variable setted to true
.subscribe(res => {
//logic
});
ngOnDestroy(){
this.isAlive = false;
}
组件销毁时自动退订
this.s1 = someObservable.subscribe((value) => {
//somecode
});
public yourMethod(){
this.s1.unsubscribe();
}
此订阅将存在并“有效”,直到 yourFunction
未被调用。
--
我个人喜欢使用 rxjs 运算符 takeWhile
来保持代码整洁。在一个非常大的项目或具有多个订阅的单个组件中,(IE) 30 variables: Subscription
令人困惑。因此,如果您询问何时使用 takeWhile
运算符,我的回答是:(以一个订阅为例)-> 如果您确定 unsubscribe
需要在组件被销毁时完成,请使用花点时间。如果在某个组件还“活着”的场景下需要退订,使用我写的第二个例子。
希望已经澄清了争论。