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

查看:110
本文介绍了如何在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.

ModifiedCode

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
  1. Understanding mergeMap and switchMap in RxJS
  2. The Simple Difference Between RxJS switchMap and mergeMap

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

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