序列异步可观察到的动作

时间:2019-09-16 15:43:05

标签: rxjs redux-observable

我想对多个异步动作进行排序,当它们全部完成后,发出最终动作:

const initializeEpic = (action$, state$, dependencies) =>
    action$.ofType("INITIALIZE_APP_REQUEST").pipe(
        mergeMap((action) => 
            [
                getUserRequest(),
                getCoreDataRequest(),
                // many other requests ...

                // now here I want to subscribe to GET_USER_SUCCESS,
                // GET_CORE_DATA_SUCCESS and other request "success" type's and 
                // once all are called, call initializeApp.success()
                // keep in mind that "..._SUCCESS" actions are called from
                // corresponding getUserEpic, getCoreDataEpic, etc...
            ]
        )
    )

我不确定是否要尝试以一种好的方法来实现史诗般的构图,但我的想法总之是:

  1. 通过PARENT_REQUEST动作致电父史诗
  2. 通过相应的*_CHILD_REQUEST动作调用子级史诗(子级史诗会通过action$.ofType(*_CHILD_REQUEST)对其进行捕获)
  3. 订阅父级史诗中的*_CHILD_SUCCESS动作(从子级史诗中派发)
  4. 调用了所有*_CHILD_SUCCESS个操作后,请调用PARENT_SUCCESS

1 个答案:

答案 0 :(得分:0)

我相信您正在寻找forkJoin。您可以执行以下操作:

const loadEpic = (action$, state$) =>
  action$.ofType("INITIALIZE_APP_REQUEST").pipe(
    mergeMap((action) =>
      forkJoin([
        getUserRequest(),
        getCoreDataRequest()
      ]).pipe(
        map(([users, coreData]) =>
          initializeApp.success(users, coreData)
        )
      )
    )
  )

请注意,请求是同时进行的,而不是顺序进行的。只要它们彼此不依赖,就不必按顺序进行。

此外,getUserRequest()getCoreDataRequest()必须返回一个可观察值,例如:

function getUserRequest() {
  return from(axios.get(`/endpoint`)).pipe(map(response => response.data));
}
相关问题