Redux-Observable 单个史诗中的多个动作

Redux-Observable multiple actions in single epic

我是新手,有几个类似的问题,例如 ,但我看不出它们如何适用于我的用例。

我正在使用 Subject 根据处理文件和上传到服务器发出多个事件

export function UploadSceneWithFile(scene){

  const subject$ = new Subject()

  FileToScenePreview(scene,scene.file).then(res => subject$.next(res))

  const uploader = new S3Upload({
   ....
    onError:()=>subject$.next('error'),
    onProgress: (val)=> subject$.next(val),
    onFinishS3Put: ()=>subject$.next('complete'),
  })
  uploader.uploadFile(scene.file)

  return subject$
}

想要编写一个史诗来捕获这些事件并根据返回的数据调度操作。

即。像这样

export function uploadSceneFile(action$) {
  return action$.ofType(CREATE_SCENE_SUCCESS)
    .mergeMap(({payload}) =>
      UploadSceneWithFile(payload)
        .subscribe(res => {
            console.log(res)
          if (!res.thumbName) {
            return { type: UPLOAD_SCENE_FAILED, message: 'failed' }
          } else {
            return {type: UPLOAD_SCENE_SUCCESS, payload:  res }
          }
        if (!res.value) {
            return { type: UPLOAD_SCENE_THUMB_FAILED, message: 'failed' }
          } else {
            return {type: UPLOAD_SCENE_THUMB_SUCCESS, payload:  res }
          }
        })
    )
}

我收到此错误:

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

我可以通过控制台记录结果,但我没有发送任何操作。我有什么想法吗?

发生的事情是您在 mergeMap 中返回订阅,而不是它期望的 Observable。而不是使用 subscribe 看起来你想使用 map

export function uploadSceneFile(action$) {
  return action$.ofType(CREATE_SCENE_SUCCESS)
    .mergeMap(({payload}) =>
      UploadSceneWithFile(payload)
        .map(res => { // <------------------ map, not subscribe
            console.log(res)
          if (!res.thumbName) {
            return { type: UPLOAD_SCENE_FAILED, message: 'failed' }
          } else {
            return {type: UPLOAD_SCENE_SUCCESS, payload:  res }
          }
        if (!res.value) {
            return { type: UPLOAD_SCENE_THUMB_FAILED, message: 'failed' }
          } else {
            return {type: UPLOAD_SCENE_THUMB_SUCCESS, payload:  res }
          }
        })
    )
}

在 redux-observable 中你几乎永远不会调用 subscribe 自己,而是组合 Observables。您唯一一次使用它的情况主要是与不太常见的自定义运算符一起使用。