redux-saga:动作和事件通道之间的竞争
redux-saga: race between action and event channel
我想使用 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
不需要是生成器函数(就像您在原始问题中那样)
我想使用 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
不需要是生成器函数(就像您在原始问题中那样)