【发布时间】:2023-03-29 15:31:01
【问题描述】:
这个问题可能与redux-observable 或rxjs 或两者有关。
我正在寻找一种通过特定操作开始、停止或恢复史诗的方法。例如,epic(已经是史诗 middelware 的一部分)在收到动作 {type: 'START'} 时将处于活动状态,但在收到动作 {type: 'END'} 时将处于非活动状态。这可能吗?
【问题讨论】:
标签: rxjs redux-observable
这个问题可能与redux-observable 或rxjs 或两者有关。
我正在寻找一种通过特定操作开始、停止或恢复史诗的方法。例如,epic(已经是史诗 middelware 的一部分)在收到动作 {type: 'START'} 时将处于活动状态,但在收到动作 {type: 'END'} 时将处于非活动状态。这可能吗?
【问题讨论】:
标签: rxjs redux-observable
您可以使用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>
【讨论】: