我一直在编写代码,如下所示:
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.
}
}这是反模式吗?如果要求是这样的,我应该做什么呢?
发布于 2018-07-18 04:07:48
我想说,这绝对是一种反模式,原因如下:
next通知。next通知--因为订阅服务器将同步取消订阅。该模式只适用于只发出单个next通知的同步源。在这种情况下,unsubscribe是多余的,因为订阅者将在源完成时自动取消订阅。
如果您知道源只发出一个next通知,则应该忽略unsubscribe。如果不确定,则应在订阅点使用first或take(1)。
还有另一种机制可以用来在收到第一个next通知时取消订阅,但这不是我鼓励的机制,因为它需要使用一个非箭头函数。
当调用next处理程序时,订阅服务器被用作上下文,因此可以在其上调用unsubscribe,如下所示:
source.subscribe(function (value) {
/* do something with value */
this.unsubscribe();
});https://stackoverflow.com/questions/51393022
复制相似问题