【问题标题】:How to refactor a subscribe inside a subscribe in rxjs如何在 rxjs 中的订阅中重构订阅
【发布时间】:2018-10-01 18:03:08
【问题描述】:

例如:

this.saveSubscription$ = this.ds.onSave$.subscribe(x => 
  this.sb.updateMachineTool(this.viewEditModel.viewEditModel).subscribe(x = {
    console.log('alert results', x)
  })
)

this.ds.onSave$ 是在单击不同组件上的保存按钮时触发的主题。

this.sb.updateMachineTool 是更新特定工具的 httpClient 帖子

我应该使用某种类型的地图,这样我就不会同时订阅这两个区域了吗?

如何重构这段代码?

【问题讨论】:

    标签: angular rxjs angular6 rxjs5 rxjs6


    【解决方案1】:

    重构您的代码您可以使用
    mergeMap
    switchMap

    您的问题是switchMap 的完美用例。因为正如您所提到的,this.ds.onSave$ 是一个主题,当单击不同组件上的保存按钮时触发。
    switchMap 在这种情况下为您提供的优势是,如果重复单击该按钮,它将自动取消所有旧订阅(在您的情况下为 Http 调用中)。

    修改代码

    this.saveSubscription$ = this.ds.onSave$.pipe(switchMap(()=> 
      this.sb.updateMachineTool(this.viewEditModel.viewEditModel)
      )
    ).subscribe(x = {
        console.log('alert results', x)
      });
    

    了解更多

    1. Understanding mergeMap and switchMap in RxJS
    2. The Simple Difference Between RxJS switchMap and mergeMap

    【讨论】:

    • 这太棒了,正是我所需要的。据我了解,mergemap 中的内容会自行完成,我仍然需要取消订阅 this.saveSubscription$ 对吗?
    • @ghoul Mate MergeMap 允许同时激活多个内部订阅,这在您的情况下是不可取的,除了取消订阅被认为是一种好的做法。
    • 对不起,我的意思是switchMap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2021-12-19
    • 2022-07-31
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多