Matej
Matej

Reputation: 186

Angular NgRx Effect concatMap multiple HTTP requests based on condition

I have an action which is mapped to HTTP request via concatMap method because I need those HTTP requests to be sequenced. I'd like to improve this behavior by sequencing only HTTP requests with same object ID that's sent in the action.

This is the code I have that's working, but making all the requests sequentials. I am using it for inline editing of records and I want to make it that if user changes value1 for record with ID:1 and then changes value2 for ID:1 these calls will be sequential, but if he changes value1 for record with ID:2 in the meantime then it would do the save request for record with ID:2 in parallel with those save requests for record with ID:1. Is this possible with some map method?

@Effect()
saveEffect = this.actions.pipe(
  ofType(saveAction),
  concatMap(action => this.service.save(action.oID, action.saveData)
    .pipe(
      map(...),
      catchError(...)
    )
  )
);

Upvotes: 2

Views: 1621

Answers (1)

frido
frido

Reputation: 14099

You can use groupBy to group your actions by id. This operator will emit every incoming action on an Observable for its specific group.

saveEffect = this.actions.pipe(
  ofType(saveAction),
  groupBy(action => action.oID),
  mergeMap(group$ => group$.pipe(
    concatMap(action => this.saveAction(action))
  ))
);

saveAction(action): Observable<any> {
  return this.service.save(action.oID, action.saveData).pipe(
    map(...),
    catchError(...)
  )
}

Upvotes: 1

Related Questions