问题
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
- Understanding mergeMap and switchMap in
RxJS
- The Simple Difference Between RxJS switchMap and mergeMap
来源:https://stackoverflow.com/questions/52596486/how-to-refactor-a-subscribe-inside-a-subscribe-in-rxjs