2017-08-06 40 views

回答

2

你可以使用的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>

相關問題