如何在redux-saga中对请求进行分组

时间:2017-10-04 17:33:25

标签: javascript reactjs redux redux-saga redux-observable

我需要为多个图表加载数据。我还希望仅在图表设置更改(distinctUntilChanged)时发送请求并删除旧请求(不再反映当前设置 - 这就是switchMap所做的事情)。在rxjsredux-observable中,它看起来像这样:

export const chartsEpic = action$ =>
  action$
    .ofType('CHART_DATA_REQUESTED')
    // group actions by chart id...
    .groupBy(action => action.meta.chartId)
    // ...and for each chart:
    .map(actionsByChart$ =>
      actionsByChart$
        // continue only if settings change
        .distinctUntilChanged((a1, a2) => compare(a1.payload.settings, a2.payload.settings))
        // load data, but drop old requests when we get new settings
        .switchMap(action => 
          Observable.fromPromise(fetchChartData(action.payload.settings))
            .map(data => ({type: 'CHART_DATA.SUCCESS', payload: data, meta: action.meta))
            .catch(error => Observable.of({type: 'CHART_DATA.FAILURE', payload: error, meta: action.meta}))
        )
    )
    // combine actions for all charts into one output stream
    .mergeAll();

redux-saga中的可比代码是什么?

1 个答案:

答案 0 :(得分:1)

实现它的通用方法:

function* syncChartsFlow(){
     var fetchTask = null;
     while(true){
          yield take([INITIAL_FETCH, SETTINGS_CHANGED])
          if(fetchTask){
              yield cancel(fetchTask)
          }
          fetchTask = yield fork(fetchChartsInfo)
     }
}

function* fetchChartsInfo(){
  // fetch info here
}