此问题可能与redux-observable
或rxjs
或两者有关。
我正在寻找一种通过特定动作来启动,停止或恢复史诗的方法。例如,史诗(已经是史诗middelware的一部分)将在收到操作{type: 'START'}
时处于活动状态,但在收到操作{type: 'END'}
时将处于非活动状态。这可能吗?
答案 0 :(得分:2)
您可以使用switchMap
和filter
的组合来执行此操作(假设所有操作包括开始/结束操作来自同一来源)
如果您的开始/结束操作来自单独的来源,则更容易,那么您可以跳过分离源流的步骤。
运行下面的代码示例以查看它的实际效果。
// this would be your source
const actions$ = new Rx.Subject();
// in this example controllActions and dataActions are derived from the same stream,
// if you have the chance to use 2 seperate channels from the start, do that
const controllActions$ = actions$
.filter(action => action.type === "END" || action.type === "START");
const dataActions$ = actions$
.filter(action => action.type !== "END" && action.type !== "START");
const epic$ = controllActions$
.switchMap(action => {
if (action.type === "END") {
console.info("Pausing stream");
return Rx.Observable.never();
} else {
console.info("Starting/Resuming stream");
return dataActions$;
}
});
epic$.subscribe(console.log);
// simulating some action emissions, the code below is _not_ relevant for the actual implementation
Rx.Observable.from([
"Some data, that will not be emitted...",
{type: "START"},
"Some data, that _will_ be emitted...",
"Some more data, that _will_ be emitted...",
{type: "END"},
"Some data, that will not be emitted...",
"Some data, that will not be emitted...",
{type: "START"},
"Some data, that _will_ be emitted...",
"Some more data, that _will_ be emitted..."
])
.concatMap(d => Rx.Observable.of(d).delay(400))
.subscribe(actions$);
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>