Last active
May 6, 2018 07:53
-
-
Save puemos/f68f3edc78bcc248af9e7c01def3f0d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { buffers, channel } from "redux-saga"; | |
| import { all, call, fork, put, take } from "redux-saga/effects"; | |
| /** | |
| * creates a queue | |
| * | |
| * @param {GeneratorFunction} [handler] request handler | |
| * @param {number} [concurrent=1] number of workers | |
| */ | |
| function* ConcurrentTaskQueue(handler, concurrent = 1) { | |
| const addTaskChannel = yield call(channel, buffers.expanding()); | |
| function* watchRequests() { | |
| try { | |
| // create a channel to queue incoming requests | |
| const runChannel = yield call(channel, buffers.expanding()); | |
| // create n worker 'threads' | |
| yield all(Array(concurrent).fill(fork(handleRequest, runChannel))); | |
| while (true) { | |
| const { payload } = yield take(addTaskChannel); | |
| yield put(runChannel, payload); | |
| } | |
| } finally { | |
| } | |
| } | |
| function* handleRequest(chan) { | |
| while (true) { | |
| const payload = yield take(chan); | |
| yield handler(payload); | |
| } | |
| } | |
| return { | |
| watcher: watchRequests, | |
| addTaskChannel | |
| }; | |
| } | |
| export default createQueue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment