Search code examples
rxjsrace-conditionredux-observablecancellation

In a redux-observable epic, why can we filter the action stream of a type but still get access the action stream of another type


In the cancellation examples of redux-observable official doc, we firstly filter the action stream action$ by a type, and then race an ajax call with the action stream of another type. I don't understand how can it be possible for action$ of type FETCH_USER_CANCELLED pass through the first ofType(FETCH_USER) filter.

Here is an example

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => race(
    ajax.getJSON(`/api/users/${action.payload}`).pipe(
      map(response => fetchUserFulfilled(response))
    ),
    action$.pipe(
      ofType(FETCH_USER_CANCELLED),
      map(() => incrementCounter()),
      take(1)
    )
  ))
);

Why don't we need 'FETCH_USER_CANCELLED' at the first ofType filter?

action$.pipe(
  ofType(FETCH_USER, FETCH_USER_CANCELLED),
  ...

It would be grateful if someone can explain.


Solution

  • In the above example you are using the unfiltered action$ stream twice. The ofType(FETCH_USER) filter only applies to the subsequent operators in the pipe (aka the mergeMap after it).