Search code examples
angularrxjsreactive-programming

SwitchMap from one outer observable to multiple innser observables


I have a method which makes a http request to delete all records and then makes another http request to add a new record, for each record in the records array (I am not expecting the below code to work, it's just to illustrate what I'm trying to achieve):

addNewRecords(recordToDelete: Record, recordsToAdd: Record[]) {
    this.http.delete(`${this.baseUrl}/delete`, recordToDelete).pipe(
      switchMap(() => {
        recordsToAdd.forEach(record => {
          this.http.post(`${this.baseUrl}/add`, record);
        });
      })
    );
  }

I want to use RXJS to subscribe the outer observable, then call the inner observables concurrently.

Is there a way this can be achieved with RXJS?


Solution

  • With this code the inner(post) requests will be made parallel but after delete request:

    addNewRecords(recordToDelete: Record, recordsToAdd: Record[]=[]) {
        this.http.delete(`${this.baseUrl}/delete`, recordToDelete).pipe(
          switchMap(() => {
            if(recordsToAdd.length === 0) return of([])
            const newRecords$ = recordsToAdd.map(record => {
              return this.http.post(`${this.baseUrl}/add`, record);
            });
            return forkJoin(newRecords$)
          })
        );
      }
    

    Does it solve your problem ?