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)
      然后你不必
      unsubscribe()
      @Envil这取决于你想要什么:
      首先
      take(1)
      是不同的<代码>第一个
      对于未发出下一个
      通知而完成的源将出错<代码>接受(1)不会。是的,我知道。我不想在这里列出可能的操作员。