我们可以将 redux-batch-middleware 与 redux-observable 一起使用吗?

Can we use redux-batch-middleware with redux-observable?

const fetchListEpic = (action$, store) =>
  action$.ofType('LOAD_LIST')
    .switchMap(() =>
      concat$(
        of$(openLoader()),
        fromPromise$(fetchListFromServer())
          .flatMap(list => of$(loadListSucceeded(list), closeLoader()))
          .catch(e =>
            of$(
              openSnackbar('ERROR'),
              closeLoader(),
            ),
        ),
     )
  );

此处 loadListSucceededcloseLoader 操作将被一个接一个地调度,这将导致多次重新渲染组件。

redus-observable 是否也可以批处理多个操作?


更新:

我们可以使用 https://github.com/mrydengren/redux-batch-middleware 吗? redux-batch-middleware 需要一系列操作,但 redux-observable 仅适用于对象。

redux-batched-actions 与 redux-observable 配合得很好。这是一个演示,您可以在控制台中看到它只重新呈现一次,尽管依次有 PONGSECOND_PONG

https://jsbin.com/kewomex/edit?js,console,output


根据您的编辑和评论进行编辑:

Can we use https://github.com/mrydengren/redux-batch-middleware? The redux-batch-middleware expects array of actions but redux-observable works only for objects.

是的!事实上,您可以 [几乎] 使用任何具有 redux-observable 的中间件。 redux-observable 本身对您 epics 发送的内容一无所知。它只是:

rootEpic(action$, store).subscribe(store.dispatch)

有了这些知识,您接下来需要注意中间件是按照从左到右提供给 applyMiddleware 的顺序应用的。您可以将其视为 store.dispatch 将分派的任何内容传递给第一个中间件,然后选择执行某些操作 and/or 然后将该操作传递给下一个中间件,等等

因此,虽然 redux-observable 本身并不关心操作的外观,但您的 epics 可能会关心。例如ofType 运算符。这可能不会导致任何问题,因为如果分派的 "action" 实际上是一个动作数组,action.type 将只是 undefined 并被 ofType 无误地过滤掉。无论如何,将 redux-batch-middleware 放在 redux-observable 之前可能是个好主意,这样数组就会被消耗,每个内部动作都会在返回给你的 epics 之前发出。这也意味着这些动作中的每一个也可以由其他 epics 处理,这太棒了。

https://jsbin.com/yemixet/edit?js,console,output

import { batch, batching } from 'redux-batch-middleware';

const store = createStore(batching(rootReducer),
  applyMiddleware(batch, epicMiddleware)
);