增加id配方 - takeEvery,但排队工作人员直到工作人员已经取得了id

时间:2017-08-26 19:26:15

标签: redux-saga

在redux-saga中有增量id的最佳实践方法吗?

这就是我这样做的方式,但是如果同时调度了多个请求,则多个内容会获得相同的ID:

我的减速机数据形状如下:

const INITIAL = {
    lastId: -1,
    entries: []
}

这是我的传奇:

function* requestDownloadWorker(action: RequestAction) {

    // other workers should wait

    const id = (yield select()).downloads.lastId;
    yield put(increment());
    console.log('incremented the lastId incremented, for whoever needs it next');
    // other workers can now continue

    // below logic - should happen in parallel with other workers
}
function* requestDownloadWatcher() {
    yield takeEvery(REQUEST, requestDownloadWorker);
}
sagas.push(requestDownloadWatcher);

我认为我需要takeEvery,但排队worker直到前一个worker声明已完成id,这可能吗?

1 个答案:

答案 0 :(得分:2)

您可以创建一个actionChannel来缓冲所有REQUEST操作,直到您“接受”它们为止。

import { actionChannel, select, take } from 'redux-saga/effects'
...

function* requestDownloadWorker() {
  const channel = yield actionChannel(REQUEST)
  while (true) {
    const action = yield take(channel)
    const id = (yield select()).downloads.lastId
    yield put(increment())

    yield fork(doOtherParallelStuff)
  }
}

它应该有用。