redux-saga:动作与事件频道之间的竞赛

时间:2018-08-11 14:27:22

标签: ecmascript-6 redux 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 
}

1 个答案:

答案 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不必是生成器函数(就像您在原始问题中一样)