redux-saga channel limit sample
by Yoshiharu Kamata
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/redux-saga.js"></script>
JavaScript
const {
take,
put,
fork,
call
} = ReduxSaga.effects;
const {
channel,
takeEvery
} = ReduxSaga;
const createSagaMiddleware = ReduxSaga.default
function heavyProcess() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, 2000);
});
}
function* watchRequests() {
// create a channel to queue incoming requests
const chan = yield call(channel);
// create 3 worker 'threads'
for (let i = 0; i < 1; i++) {
yield fork(handleRequest, chan);
}
yield * takeEvery('request', function*(action) {
// dispatch to the worker thread
yield put(chan, action);
});
}
function* handleRequest(chan) {
while (true) {
const action = yield take(chan);
console.log('start: ', action.payload.id);
yield call(heavyProcess);
console.log('end: ', action.payload.id);
}
}
function* saga() {
yield fork(watchRequests);
}
const sagaMiddleware = createSagaMiddleware();
const store = Redux.createStore(
() => {},
Redux.applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(saga);
// dispatch
for (let i = 0; i < 20; i++) {
store.dispatch({
type: 'request',
payload: {
id: i
}
});
}