rxjsredux-observable

Redux Observable: If the same action is dispatched multiple times, how do I cancel one of them?


Say, I have this epic:

export const getUserEpic = action$ => action$
  .ofType(t.GET_USER)
  .mergeMap(action => Observable
    .from(query.findUser(action.uid))
    .map(user => ({ type: t.GET_USER_SUCCESS, user }))
    .takeUntil(action$.ofType(t.GET_USER_CANCELLED))

Then, somewhere I dispatched t.GET_USER multiple times:

dispatch({ type: t.GET_USER, uid: 'uid1' })
dispatch({ type: t.GET_USER, uid: 'uid2' })
dispatch({ type: t.GET_USER, uid: 'uid3' })

How do I cancel one of them? For example:

dispatch({ type: t.GET_USER_CANCELLED, uid: 'uid2' })

AFAIK, .takeUntil(action$.ofType(t.GET_USER_CANCELLED)) will cancel all t.GET_USER actions. I need to cancel only one.


Solution

  • You can use a .filter() predicate to only unsubscribe your mergeMap for the exact uid you are looking for:

    export const getUserEpic = action$ => action$
      .ofType(t.GET_USER)
      .mergeMap(action => Observable
        .from(query.findUser(action.uid))
        .map(user => ({ type: t.GET_USER_SUCCESS, user }))
        .takeUntil(
          action$
            .ofType(t.GET_USER_CANCELLED)
            .filter(act => act.uid === action.uid)
        )