如何使用 Redux Observable 填充商店并按顺序等待 return?

How to populate the store and sequentially await return using Redux Observable?

我正在尝试使用 Redux Observable 调用一个动作来获取一些数据,等待它 return,然后获取更多依赖于它的数据。

我有一个史诗,它通过获取 FetchTodos 来填充商店。这会监听 FETCH_TODOS 操作,然后调用我的待办事项 API 并填充 {todos: [] } =

我的店里也有一个评论区todoComments。但是,我只想在 FETCH_TODOS return 编辑并填充商店后填充 todoComments

在命令式代码中,这可能看起来像:

let todos = await api.get('/todos');
await dispatch("FETCH_TODO_COMPLETE", todos)
let firstId = getState().todos[0].id
let comments = await api.get(`/todos/${firstId}/comments')
await dispatch("FETCH_COMMENTS_COMPLETE", { todo_id: firstId, comments})

我看到的最接近这个的是 Redux Observable Repo 中的 this issue,但我不明白如何有效地做到这一点。这对我来说是一个很常见的场景。

我想重用尽可能多的代码。在这个例子中,我可以从多个组件调度 FETCH_TODOS

我如何使用 Redux-Observable 完成此操作?

根据我们在评论中的对话:

在 redux-observable 中,您可以通过多种方式对事物进行排序。你可以使用普通的 RxJS 在一个史诗中完成所有这些,或者你可以将它们分成多个。如果将它们分开,后续的史诗将监听前一个史诗已完成其任务的信号。像这样:

// this assumes you make your `api.get` helper return an Observable
// instead of a Promise which is highly advisable.
// If it doesn't, you could do:
//   Observable.from(api.get('/url'))
// but Promises are not truly cancellable which can cause max
// concurrent connections issues

const fetchTodosEpic = action$ =>
  action$.ofType('FETCH_TODOS')
    .switchMap(() =>
      api.get('/todos')
        .map(todos => ({
          type: 'FETCH_TODOS_COMPLETE',
          todos
        }))
    );

const fetchComments = action$ =>
  action$.ofType('FETCH_TODOS_COMPLETE')
    .switchMap(({ todos }) =>
      api.get(`/todos/${todos[0].id}/comments`)
        .map(comments => ({
          type: 'FETCH_COMMENTS_COMPLETE',
          comments
        }))
    );