0
votes

In short, I would like to apply a switchMap to observables depending on their payload.

I currently have an epic with redux-observable that performs GETs on /api/document/{name}. I include name in the payload of my actions. The challenge is that I only filter based on the action type, and so I don't know how to filter dynamically based on the action's payload too.

const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    // TODO: Should filter and then switchMap based on different documentName
    mergeMap(action =>
      merge(
        ApiUtils.documents.fetch(action.payload).pipe(
          mergeMap(response => [
            documentActions.fetchSuccess({
              name: action.payload,
              data: response.data,
            }),
          ]),
          catchError(err => of(documentActions.fetchFailure(err)))
        )
      )
    )
  );

If I made this mergeMap a switchMap, it would apply a switchMap independent of the action value. Instead, I would just like to use a switchMap if action.payload is the same.

1

1 Answers

0
votes

Discovered the groupBy command and came up with this... does this seem reasonable?

const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    groupBy(({ payload }) => payload),
    mergeMap(group =>
      group.pipe(
        switchMap(action =>
          merge(
            ApiUtils.documents.fetch(action.payload).pipe(
              mergeMap(response => [
                documentActions.fetchSuccess({
                  name: action.payload,
                  data: response.data,
                }),
              ]),
              catchError(err => of(documentActions.fetchFailure(err)))
            )
          )
        )
      )
    )
  );