是否可以通过发布动作来启动/停止/恢复可重复观察的史诗?

问题描述:

这个问题可能是关于redux-observablerxjs或两者。是否可以通过发布动作来启动/停止/恢复可重复观察的史诗?

我正在寻找一种方法来启动,停止或通过特定操作恢复史诗级别。例如,史诗(已经是史诗middelware的一部分)将在收到动作{type: 'START'}时激活,但在收到动作{type: 'END'}时将失效。这可能吗?

你可以使用的switchMapfilter的组合来做到这一点(假设所有行动含的开始/结束动作都来自相同的源)

如果你开始/结束动作是从未来单独的源代码更容易,那么你可以跳过分离源码流的步骤。

运行下面的代码示例以查看它的行为。

// 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>