是否可以通过发出动作来开始/停止/恢复redux-observable史诗?

Huy*_*yen 6 rxjs redux-observable

这个问题可能是约redux-observablerxjs或两者兼而有之.

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

ols*_*lsn 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$);
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
Run Code Online (Sandbox Code Playgroud)