Is there any way to chain n amount of http requests together using RxJS?

Viewed 2154

In the code below I have a User object which can have a variable amount of account ids associated with it. When a user gets updated an additional request should be made for each account contained in the user object:

class User {

  id: number;

  accountIds: Array<number>;
}

// Side effects class
@Effect()
update$ = this.actions$
  .ofType('USER_UPDATE')
  .switchMap(action => {

    let user = action.payload;

    for (let accountId of user.accountIds) {
      let account = { id: accountId, userIds: [user.id] };

      // Is there any way to chain these api calls with switch maps
      // and then finally switch map to the user request below?
      return this.apiService.post(`/accounts/${account.id}`, account);
    }

    return this.apiService.post(`/users/${userid}`, user);
  }

Is there any way using RxJS to chain those calls together using switchMap (or something similar) so that the observable isn't considered complete until all subsequent requests have completed without having to write some kind of custom recursive logic?

3 Answers
Related