如何在 rxjs 的订阅中重构订阅 [英] How to refactor a subscribe inside a subscribe in rxjs

查看:26
本文介绍了如何在 rxjs 的订阅中重构订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

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

this.ds.onSave$ is a subject that triggers when a save button on a different component is clicked.

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

this.sb.updateMachineTool is an httpClient post that updates a specific tool

我应该使用某种类型的地图,以便我不订阅这两个区域吗?

should I be using some type of map so i'm not subscribing to both areas?

如何重构这段代码?

推荐答案

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

To Refactor your code You can use
mergeMap
switchMap

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

your question is the perfect use case for switchMap. because as you have mentioned this.ds.onSave$ is a subject that triggers when a save button on a different component is clicked.
The advantage switchMap gives you in this scenario is it will cancel all the old subscription(Http Call in Progress in your case) automatically if the button is clicked repeatedly.

修改后的代码

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

更多

  1. 理解mergeMap和switchMap中的RxJS
  2. 简单的区别在 RxJS switchMap 和合并地图

这篇关于如何在 rxjs 的订阅中重构订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆