我试图在给定单一来源$动作的情况下从史诗中返回2个单独的值。但是 - 似乎我只能通过显式订阅内部Observable来做到这一点。我的史诗目前看起来像这样:
export const orderItemEpic = action$ =>
action$.ofType(ORDER_ITEM)
.switchMap(action => Observable.of(
api.createOrder(action.payload.order),
api.updateItem(action.payload.item, action.payload.item._id)
))
.map(val => console.log('Outer Observable', val));
然而,这只会发出第一个api请求的承诺(即使两者都被调用)
我可以同时获得这两个值的唯一方法是明确订阅内部Observable,如下所示:
export const orderItemEpic = action$ =>
action$.ofType(ORDER_ITEM)
.switchMap(action => Observable.of(
api.createOrder(action.payload.order),
api.updateItem(action.payload.item, action.payload.item._id)
).map(val => val).subscribe(v => console.log('Inner Observable', v))
.map(val => console.log('Outer Observable', val)); //never gets called
但是现在我的'Outer'Observable没有被映射。
当我用JSBin模拟它时,似乎第一个例子应该从两个api调用中发出响应。 http://jsbin.com/cejolegixo/edit?js,console
我想我只是想知道这是否是在redux-observable中的某些怪癖,或者我是否做了不正确的事情。
谢谢
答案 0 :(得分:0)
这是因为你有3个级别的Observable正在进行中。
这只会发出第一个api请求的承诺
如果您使用
,您的JSBin会更准确地镜像代码// First Mock API
const firstAPI = res => Rx.Observable.of({...res})
// Second Mock API
const secondAPI = res => Rx.Observable.of({...res})
因此,修复是“合并”内部可观察量。
// map value from source into inner observable, when complete emit result and move to next
const stream = source$.switchMap(action => Rx.Observable.merge(
firstAPI(action.payload.a),
secondAPI(action.payload.b)
))
参考JSBin
顺便说一句,你可以flatMap
代替switchMap
。取决于你想要的行为。
switchMap
会在第一个订单到达时取消第一个订单,而第一个订单是第一个订单(如果它们是不同的订单,则会显示不良)。