【问题标题】:Redux Observable: If the same action is dispatched multiple times, how do I cancel one of them?Redux Observable:如果多次分派相同的操作,我如何取消其中一个?
【发布时间】:2017-11-28 09:58:46
【问题描述】:

说,我有这部史诗:

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

然后,在某处我多次派出t.GET_USER

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

如何取消其中一个?例如:

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

AFAIK,.takeUntil(action$.ofType(t.GET_USER_CANCELLED)) 将取消所有 t.GET_USER 操作。我只需要取消一个。

【问题讨论】:

  • 您可以使用switchMap 代替mergeMap,但这实际上取决于您的应用程序的逻辑。

标签: rxjs redux-observable


【解决方案1】:

您可以使用.filter() 谓词仅取消订阅您要查找的确切uid 的mergeMap:

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

【讨论】:

  • 这真是太棒了。非常感谢。
猜你喜欢
  • 2017-03-18
  • 2019-03-19
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多