【问题标题】:rxjs/redux-observable dynamic filtering based on different payloadsrxjs/redux-observable 基于不同payload的动态过滤
【发布时间】:2020-05-30 00:11:20
【问题描述】:

简而言之,我想根据有效负载将switchMap 应用于可观察对象。

我目前有一个带有 redux-observable 的史诗,它在 /api/document/{name} 上执行 GET。我将name 包含在我的操作的有效负载中。挑战在于我只根据动作类型进行过滤,所以我也不知道如何根据动作的有效负载动态过滤。

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)))
        )
      )
    )
  );

如果我将此 mergeMap 设为 switchMap,它将应用一个独立于操作值的 switchMap。相反,如果action.payload 相同,我只想使用 switchMap。

【问题讨论】:

    标签: rxjs redux-observable


    【解决方案1】:

    发现了groupBy 命令并想出了这个……这看起来合理吗?

    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)))
                )
              )
            )
          )
        )
      );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2016-12-02
      • 2017-12-13
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多