我熟悉React和Redux,但对RxJS和redux-observable来说还是个新手.
我正在研究一个我已经设法解决的流程,看起来像这样:
const reducer = (state, action) => {
switch(action.type) {
// some other cases here
case Types.LOCATION_GEOCODED:
const { address, place_id } = action
return {...state, address, place_id }
}
}
const updateLocationEpic = (action$, store) =>
action$.ofType(Types.UPDATE_LOCATION)
.mergeMap((action) =>
Observable.fromPromise(reverseGeocode(store.getState().location))
.map(({address, place_id}) => ({type: Types.LOCATION_GEOCODED, address, place_id}))
)
const broadcastLocationEpic = (action$, store) =>
action$.ofType(Types.LOCATION_GEOCODED)
.map((action) => ({type: Types.NEW_CURRENT_LOCATION, store.getState().location}))
第一个史诗在异步请求之后发出LOCATION_GEOCODED动作,然后减速器“完成”位置信息,最后第二个史诗从状态获取完整位置并广播它.
关键是确保在reducer处理完上一个操作(LOCATION_GEOCODED)后触发NEW_CURRENT_LOCATION操作,因为它需要查询刚刚更新的状态.
上面的代码有效,但我想知道它是否可以某种方式在一个史诗上表达,特别是因为我有另一个案例,我需要等待并行请求产生的两个动作所以我需要做类似于什么的事情你会用Promise.all那种模式实现
有没有更好的方法在单个史诗上执行此操作?
最佳答案
const updateLocationEpic = (action$, store) =>
action$.ofType(Types.UPDATE_LOCATION)
.mergeMap((action) => Observable.merge(
Observable.fromPromise(reverseGeocode(store.getState().location))
.map(({ address, place_id }) => ({ type: Types.LOCATION_GEOCODED, address, place_id })),
action$.ofType(Types.LOCATION_GEOCODED)
.map((action) => ({ type: Types.NEW_CURRENT_LOCATION, location: store.getState().location }))
));