Redux-observable: how to wait for multiple async requests then perform action in an epic

让人想犯罪 __ 提交于 2019-12-11 16:15:26

问题


I'd like to wait for the two http requests below to finish before triggering another action. However, the http requests were not fired. Only the DASHBOARD_INIT action was triggered:

export const dashboardInitEpic = (action$: any) =>
    action$.ofType(InitActionTypes.DASHBOARD_INIT)
        .switchMap((action: ActionDashboardInit) =>
           zip$(
             of$(fetchConfig(action.payload)),
             of$(fetchPermission(action.payload))
           ).switchMap(() =>
           zip$(
             action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
             action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
           ).switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
         )
      );

To get the http requests fired, I had to do the following which is not exactly what I want. Concat forces the http requests to be in sequence and the code below listens to FETCH_CONFIG_FULFILLED and FETCH_PERMISSION_FULFILLED in sequence, which breaks sometimes depending on whether fetchConfig's response comes back first.

export const dashboardInitEpic = (action$: any) =>
    action$.ofType(InitActionTypes.DASHBOARD_INIT)
      .mergeMap((action: ActionDashboardInit) =>
         concat$(
           of$(fetchConfig(action.payload)),
           of$(fetchPermission(action.payload)),
           action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
           action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED)
             .take(1)
             .switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
      )
    );

Any help is greatly appreciated. Have been stuck on this for a few days. Thanks a lot!


回答1:


Try this:

export const dashboardInitEpic = (action$: any) =>
  action$
    .ofType(InitActionTypes.DASHBOARD_INIT)
    .mergeMap((action: ActionDashboardInit) =>
      concat$(
        of$(fetchConfig(action.payload)),
        of$(fetchPermission(action.payload)),
        zip$(
          action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
          action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
        ).mapTo({ type: InitActionTypes.DASHBOARD_INIT_COMPLETE })
      )
    );


来源:https://stackoverflow.com/questions/50951633/redux-observable-how-to-wait-for-multiple-async-requests-then-perform-action-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!