Redux-Saga:动作和事件频道之间的竞赛



我想使用 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 
}

这应该可以做到:

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
}
}

在我看来,代码非常可读。 您在两个take之间设置一个race,然后对获胜者采取行动。

请注意,createEventChannel不需要是生成器函数(就像您在原始问题中所做的那样(

最新更新