Rxjs 可观察。订阅(..)。取消订阅();反模式。
我发现自己一直在写这样的代码:Rxjs 可观察。订阅(..)。取消订阅();反模式。,rxjs,Rxjs,我发现自己一直在写这样的代码: class WidgetService { getWidgets() { return this.authService.user.pipe( //authService.user is an Observable, that emits the currently authenticated users. first(user => user!=null), //Make sure a null object
class WidgetService {
getWidgets() {
return this.authService.user.pipe( //authService.user is an Observable, that emits the currently authenticated users.
first(user => user!=null), //Make sure a null object isn't coming through
switchMap(user => {
return this.collection.getWhere("widget.ownerId", "==", user.id); //Get all the widgets for that user
})
);
}
}
class WidgetDisplayComponent {
ngOnInit() {
this.widgetService.getWidget().subscribe(widget => this.widget = widget).unsubscribe(); //Subscribe to cause the Observable to pipe, get the widget, then unsubscribe.
}
}
这是反模式吗?如果要求是:
- 为了获取我正在获取的项目,我需要依赖于另一个可观察对象李>
- 我只需要买一次这个东西李>
- 出于以下原因,我认为这绝对是一种反模式:
- 对于同步源,不能保证您只会收到一个
通知next
- 使用异步源,您将不会收到任何
通知,因为订户将同步取消订阅next
通知的同步源。在这种情况下,next
是多余的,因为当源完成时,订户将自动取消订阅 依我看,如果你知道源代码只发出一个取消订阅
通知,你应该忽略next
。如果您不确定,您应该在订阅点使用取消订阅
或first
take(1)
在收到第一个
通知时,可以使用另一种机制取消订阅,但我不鼓励使用这种机制,因为它需要使用非箭头功能 当调用next
处理程序时,订阅者被用作上下文,因此可以在其上调用next
,如下所示:unsubscribe
source.subscribe(function (value) { /* do something with value */ this.unsubscribe(); });
正确,使用
然后你不必take(1)
@Envil这取决于你想要什么:unsubscribe()
通知而完成的源将出错<代码>接受(1)不会。是的,我知道。我不想在这里列出可能的操作员。首先
对于未发出下一个和
是不同的<代码>第一个take(1)
- 对于同步源,不能保证您只会收到一个