如何在单个redux可观察史诗中等待/屈服于多个动作?

时间:2017-02-03 22:56:33

标签: redux-observable

我有一个redux Saga,每次调度'WATCHLIST_FETCH_REQUEST'时会执行三种不同的操作:

function* watchFetchWatchlist() {
  yield takeLatest('WATCHLIST_FETCH_REQUEST', fetchWatchlist);
}


function* fetchWatchlist() {
  const activity = 'ACTIVITY_FETCH_WATCHLIST';
  yield put(
    addNetworkActivity(activity) // Action 1: enables a global loading indicator before request is made
  );
  const { response, error } = yield call(
    api.fetchWatchlist // make an API request
  );
  yield put(
    removeNetworkActivity(activity) // Action 2: removes the above global loading indicator after request completes
  );
  if (response) {
    yield put(
      updateUserWatchlist(response) // Action 3a: updates Redux store with data if response was successful
    );
  } else {
    yield put(
      watchlistFetchFailed(error) // Action 3b: updates Redux store with error if response failed
    );
  }
}

这个传奇的流程本质上是同步的。必须首先运行操作1以设置应用程序的全局加载状态。操作2必须在操作1之后运行,并在API响应返回后在网络活动完成时删除全局加载状态。

我对redux-observable很新,但我一直在努力寻找如何将这个传奇转换为史诗。这里有两个目标:

  1. 依次执行操作,而不是并行执行
  2. 在单个史诗中执行这些操作/流程(当类型:'WATCHLIST_FETCH_REQUEST'被触发时开始)
  3. 如何使用redux-observable实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:6)

我在这里拼凑了部分对话,找到了我的问题的答案:https://github.com/redux-observable/redux-observable/issues/62

我最终得到的结论是:

import { concat as concat$ } from 'rxjs/observable/concat';
import { from as from$ } from 'rxjs/observable/from';
import { of as of$ } from 'rxjs/observable/of';


export const fetchWatchlistEpic = (action$) => {
  const activity = 'ACTIVITY_FETCH_WATCHLIST';

  return action$.ofType('WATCHLIST_FETCH_REQUEST')
    .switchMap(() =>
      concat$(
        of$(addNetworkActivity(activity)),
        from$(api.fetchWatchlist())
          .map((data) => Immutable.fromJS(data.response))
          .switchMap((watchlist) =>
            of$(
              updateUserWatchlist(watchlist),
              removeNetworkActivity(activity),
            )
          )
      )
    );
};
尝试按顺序运行多个操作时,

concatof似乎是首选操作符。