在使用 redux-observables 开始另一个史诗之前,如何等待不同的史诗完成并更新商店?

How to wait for a different epic to finish and the store to be updated, before starting another epic with redux-observables?

在我的场景中,当应用程序加载时,我调度一个启动史诗的动作来创建一个 API 实例,这是进行其他 API 调用所必需的:

const connectApiEpic: Epic = (action$, state$) =>
  action$.pipe(
    ofType('CONNECT_API'),
    mergeMap(async (action) => {
      const sdk = await AppApi.connect({ url: apiUrl });

      return { type: 'SET_API', payload: api };
    })
  );

UI 已经加载,API 连接在后台进行。现在,如果用户单击某个搜索按钮,我必须分派另一个操作(史诗)来执行搜索,这需要 API 已经连接。

基本上,我需要做类似的事情:

const searchItem: Epic = (action$, rootState$) =>
  action$.pipe(
    ofType('SEARCH_ITEM'),
    mergeMap(async (action) => {
      const { api } = rootState$.value;

      const item = await api.search(action.item);

      return { type: 'SET_ITEM', payload: item };
    })
  );

但是,只有从 connectApiEpic 开始在商店中设置 API 才会起作用。

使用redux-observables和rxjs,怎么可能:

  1. 应用程序启动时在后台连接 api(已解决)
  2. 如果用户点击“搜索”,派遣一个史诗进行搜索,但先等待api连接,如果api 已经 连接,然后继续执行搜索

因此,如果 api 是您在 searchItem 史诗中需要等待的内容,我认为这将是一种方法:

const searchItem: Epic = (action$, rootState$) =>
  action$.pipe(
    ofType('SEARCH_ITEM'),

    mergeMap(
      // waiting for the api to connect first
      // if it's already there, everything will happen immediately
      action => rootState$.pipe(
        map(state => state.api)
        filter(api => !!api),
      ),
    ),

    mergeMap(
      api => from(api.search(action.item)).pipe(
        map(item => ({ type: 'SET_ITEM', payload: item }))
      )
    )
  );