4
這個問題可能是關於redux-observable
或rxjs
或兩者。是否可以通過發佈動作來啓動/停止/恢復可重複觀察的史詩?
我正在尋找一種方法來啓動,停止或通過特定操作恢復史詩級別。例如,史詩(已經是史詩middelware的一部分)將在收到動作{type: 'START'}
時激活,但在收到動作{type: 'END'}
時將失效。這可能嗎?
這個問題可能是關於redux-observable
或rxjs
或兩者。是否可以通過發佈動作來啓動/停止/恢復可重複觀察的史詩?
我正在尋找一種方法來啓動,停止或通過特定操作恢復史詩級別。例如,史詩(已經是史詩middelware的一部分)將在收到動作{type: 'START'}
時激活,但在收到動作{type: 'END'}
時將失效。這可能嗎?
你可以使用的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>