【问题标题】:Is there a cleaner way of organising multiple RXJS observables inside a merge?是否有一种更简洁的方法可以在合并中组织多个 RXJS 可观察对象?
【发布时间】:2023-03-21 14:01:01
【问题描述】:

下面的史诗按预期工作。在进行 api 调用之前,它会在合并运算符中调用多个操作。但是,我只是想知道有没有比我列出单独的 observables 更简洁的方法来调用重置操作。是否可以在数组中列出它们?还是其他方式?

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

【问题讨论】:

    标签: rxjs redux-observable


    【解决方案1】:

    您可以利用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
                })
              )
            )
          )
        )
      );
    

    【讨论】:

    • 答案是正确的,但您应该使用concat 而不是merge - concat 保证保持秩序。 (OP 也使用concat
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2020-09-14
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多