Is it possible to start / stop / resume the epic effect observed by reduction?

This question may be about redux-observableor rxjsor both.

I am looking for a way to start, stop, or resume the epic through concrete actions. For example, an epic (which is already part of epic multimedia) will be active when an action {type: 'START'}is received, but will be inactive when an action is received {type: 'END'}. Is it possible?

+4
source share
1 answer

To do this, you can use a combination of switchMapand filter(provided that all actions, including start / end actions, come from the same source)

/ , , .

, .

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

Source: https://habr.com/ru/post/1683082/


All Articles