如何在 rxjs 的订阅中重构订阅 [英] How to refactor a subscribe inside a subscribe in 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?
如何重构这段代码?
推荐答案
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)
});
更多
这篇关于如何在 rxjs 的订阅中重构订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!