0

I am using RxJs concatMap to control the saving of some data in my application.

this.myService.saveData(this.updatedData)
  .pipe(
    tap(data1Res => this.onData1Success(data1Res)),
    concatMap(() => this.myService.saveOne(this.OneData)),
    tap(data2Res => this.onData2Success(data2Res)),
    concatMap(() => this.myService.saveTwo(this.TwoData)),
    tap(data3Res => this.onData3Success(data3Res)),
    concatMap(() => this.myService.saveThree(this.ThreeData)),
    tap(data4Res => this.onData4Success(data4Res)),
    concatMap(() => this.myService.saveFour(this.FourData)),
  )
  .subscribe(
    res => this.onSaveSuccess(), // Reload values
    err => console.log('error while saving', err) // Save to file or db
  );

Currently this works however it also executes even if say "this.OneData" is empty or null...how can I keep it from sending essentially a NoOpp request?

Funn_Bobby
  • 647
  • 1
  • 20
  • 57
  • 1
    you can use filter(r => r !== null ) to filter nulls or anything else – Barkha Feb 26 '20 at 16:50
  • Thanks for the response so what would the call look like exactly...concatMap(filter(() => this.myService.saveOne(this.OneData) !== null)) – Funn_Bobby Feb 26 '20 at 16:54

2 Answers2

1
this.myService.saveData(this.updatedData)
  .pipe(
    tap(data1Res => this.onData1Success(data1Res)),
    concatMap(() => this.myService.saveOne(this.OneData)),
    filter(res => res !== null),
    tap(data2Res => this.onData2Success(data2Res)),
    ...

  )
  .subscribe(
    res => this.onSaveSuccess(), // Reload values
    err => console.log('error while saving', err) // Save to file or db
  );
  • Thank you for the response Cenk ...so this will not call "saveOne" if "this.OneData" is Null? – Funn_Bobby Feb 26 '20 at 17:35
  • If the saveOne's res is null then the others are not called. Filter breaks the pipe when the value is false. – Cenk Çetinkaya Feb 26 '20 at 17:39
  • Okay, what if I want "saveTwo" and " saveFour" to execute because "this.TwoData" and "this.FourData" are populated but I don't want the others to execute because they are not populated...doesn't sound like "filter" will work for that. – Funn_Bobby Feb 26 '20 at 17:59
  • Actually this pipe usage is not efficient, I don't understand what you completely do. – Cenk Çetinkaya Feb 26 '20 at 20:27
  • It's usage is to call api's in a certain order one after another to avoid nested .subscribes...so for that it's pretty efficient. – Funn_Bobby Feb 26 '20 at 20:30
0

Filter can be used like this to make sure it doesn't run if it is empty or null

this.myService.saveData(this.updatedData)
  .pipe(
    tap(data1Res => this.onData1Success(data1Res)),
    filter(res => res),
    concatMap(() => this.myService.saveOne(this.OneData)),
   ...
  )
  .subscribe(
    res => this.onSaveSuccess(), // Reload values
    err => console.log('error while saving', err) // Save to file or db
  );
Barkha
  • 702
  • 3
  • 8