我想使用redux-saga在redux动作和事件频道之间进行比赛。
export function * createEventChannel () {
return eventChannel(emit => {
MyModule.addEventListener(MyModule.MY_EVENT, emit)
return () => { MyModule.removeEventListner(MyModule.MY_EVENT, emit)}
})
}
....
function * raceWithActionAndEvent() {
const channel = yield call(createEventChannel)
// I want to race between Redux Action: 'MY_ACTION' and channel here
}
答案 0 :(得分:0)
这应该做到:
export function* raceWithActionAndEvent() {
const channel = yield call(createEventChannel);
const winner = yield race({
channel: take(channel),
action: take(MY_ACTION),
});
if (winner.action) {
// then the action was dispatched first
}
if (winner.channel) {
// then the channel emitted first
}
}
我认为该代码可读性强。您在两个race
之间设置了一个take
,然后对获胜者采取行动。
请注意,createEventChannel
不必是生成器函数(就像您在原始问题中一样)