How to refactor a subscribe inside a subscribe in rxjs

左心房为你撑大大i 提交于 2019-12-11 06:20:00

问题


For example:

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

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

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?

How can I refactor this code?


回答1:


To Refactor your code You can use
mergeMap
switchMap

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)
  });

For More

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


来源:https://stackoverflow.com/questions/52596486/how-to-refactor-a-subscribe-inside-a-subscribe-in-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!