Emilios1995
Emilios1995

Reputation: 507

Cancel sequence of ajax calls when one fails

In my store a have queue containing pending network requests. When the action ATTEMPT_FLUSH is emmited, I want to sequentially send the requests. However if one of them fails and emits ATTEMPT_FLUSH_CANCELLED, the next ones should not be attempted (until I try again in the next ATTEMPT_FLUSH, of course).

Here's what I have so far

export const attemptFlushEpic = (action$, store) =>
  action$
    .ofType(ATTEMPT_FLUSH)
    .mergeMap(() => Observable.from(store.getState().queue)) // state.queue is an array
    .concatMap(action =>
        Observable.ajax(action.url)
        .map(response => removeFromQueue(action))
        .catch(err => Observable.of(attemptFlushCancelled())));

Upvotes: 0

Views: 383

Answers (1)

Berkeley Martinez
Berkeley Martinez

Reputation: 2805

Moving up the actual ajax call should cancel the subsequent ajax on failure.

export const attemptFlushEpic = (action$, store) =>
  action$
    .ofType(ATTEMPT_FLUSH)
    .mergeMap(() => Observable.from(store.getState().queue)
      .concatMap(action => Observable.ajax(action.url)
        .map(response => removeFromQueue(action)))
      .catch(err => Observable.of(attemptFlushCancelled())))
    );

Upvotes: 2

Related Questions