Redux Observable:多次点击(两次或更多次)的分派操作

Redux Observable: dispatch action on multiple clicks (two or more)

我正在使用 redux observable 作为 redux 的中间件来处理副作用。我只想在某个指定时间段(比如 500 毫秒)内发出动作 B 超过两次时才发送动作 A

我的尝试:demo

这是史诗般的样子:

const pingEpic = action$ =>
  action$
    .buffer(action$.ofType(CLICK).throttleTime(500))
    .map(x => x.length)
    .filter(x => x >= 2)
    .mapTo({ type: PING });

此史诗正确地累积了列表中的点击次数并过滤了那些长于 2 次的点击次数,但 PING 操作是在另一次额外点击之后调度的。

我发现将复杂的 rxjs 分解成更小的部分更容易解决。

因此,您希望双击 PING,单击 PONG,而 CLICK 是唯一的事件源。

双击 Ref

const doubleClick = action$ =>
  action$.ofType(CLICK)
    .buffer(action$.ofType(CLICK).debounceTime(500))
    .map(x => x.length)
    .filter(x => x === 2)
    .mapTo({ type: PING });

单击

const singleClick = action$ =>
  action$.ofType(CLICK)
    .buffer(action$.ofType(CLICK).debounceTime(500))
    .map(x => x.length)
    .filter(x => x === 1)
    .mapTo({ type: PONG });

PING/PONG

const pingEpic = action$ =>
  Rx.Observable.merge(
    singleClick(action$), 
    doubleClick(action$)
  )

注意,它似乎可以直接将 throttleTime 替换为 debounceTime

const pingEpic = action$ =>
  action$
    .buffer(action$.ofType(CLICK).debounceTime(500))
    .map(x => x.length)
    .filter(x => x >= 2)
    .mapTo({ type: PING });

但是您不会因此而发生任何 PONG。 (加一个console.log到reducer显示流程好一点)

const pingReducer = (state = { isPinging: 'NO' }, action) => {
  console.log('reducer', action.type)
  ...

示例如下 Fiddle