1

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?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
ghoul
  • 890
  • 1
  • 10
  • 17

1 Answers1

2

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
Vikas
  • 11,859
  • 7
  • 45
  • 69
  • This is awesome and exactly what I needed. As I understand, what's in mergemap will complete itself, I will still need to unsubscribe from `this.saveSubscription$` correct? – ghoul Oct 01 '18 at 18:54
  • @ghoul Mate `MergeMap` allows for multiple inner subscriptions to be active at a time which is not desirable in your case apart from unsubscribing is considered a good practice. – Vikas Oct 01 '18 at 19:00
  • I am sorry I meant `switchMap` – ghoul Oct 01 '18 at 19:10
  • @ghoul https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods have a look – Vikas Oct 01 '18 at 19:12