有没有一种更干净的方法来在合并中组织多个RXJS可观察对象?

时间:2018-08-07 22:37:02

标签: rxjs redux-observable

以下史诗按预期工作。在进行api调用之前,它将在merge操作符内部调用多个动作。但是,我只是想知道,有没有比我列出单独的可观察对象更干净的方法来调用重置操作。是否可以在数组中列出它们?还是其他方式?

const imageUploadEpic = (action$, state$) =>
  action$.pipe(
    ofType('UPLOAD_IMAGE'),
    mergeMap(action =>
      concat(
        merge(
          of({ type: 'RESET_IMAGE' }),
          of({ type: 'RESET_COLOURS' }),
          of({ type: 'RESET_LOCALISER' })
        ),
        from(
          axios.post(`/uploads/url`, {
            url: action.src
          })
        ).pipe(
          map(response => ({
            type: 'UPLOAD_IMAGE_SUCCESS',
            data: response.data,
          })),
          catchError(error =>
            of({
              type: 'UPLOAD_IMAGE_ERROR',
              error
            })
          )
        )
      )
    )
  ); 

1 个答案:

答案 0 :(得分:2)

您可以利用concat接受ObservableInput参数并且数组是ObservableInput的事实:

const imageUploadEpic = (action$, state$) =>
  action$.pipe(
    ofType('UPLOAD_IMAGE'),
    mergeMap(action =>
      concat(
        [
          { type: 'RESET_IMAGE' },
          { type: 'RESET_COLOURS' },
          { type: 'RESET_LOCALISER' }
        ],
        from(axios.post(`/uploads/url`, { url: action.src })).pipe(
          map(response => ({
            type: 'UPLOAD_IMAGE_SUCCESS',
            data: response.data,
          })),
          catchError(error =>
            of({
              type: 'UPLOAD_IMAGE_ERROR',
              error
            })
          )
        )
      )
    )
  );