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

白昼怎懂夜的黑 提交于 2019-12-13 03:49:16

问题


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.


回答1:


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)
    )


来源:https://stackoverflow.com/questions/47528620/redux-observable-if-the-same-action-is-dispatched-multiple-times-how-do-i-canc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!