Skip to content

Instantly share code, notes, and snippets.

@therealparmesh
Created January 26, 2019 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therealparmesh/01108de3aa4035687a1d3200493ae411 to your computer and use it in GitHub Desktop.
Save therealparmesh/01108de3aa4035687a1d3200493ae411 to your computer and use it in GitHub Desktop.
Redux Saga helpers
import { call, cancel, fork, take } from 'redux-saga/effects';
export function takeLatestPerKey(patternOrChannel, worker, keySelector, ...args) {
return fork(function*() {
const tasks = {};
while (true) {
const action = yield take(patternOrChannel);
const key = yield call(keySelector, action);
if (tasks[key]) {
yield cancel(tasks[key]);
}
tasks[key] = yield fork(worker, ...args, action);
}
});
}
export function takeLeadingPerKey(patternOrChannel, worker, keySelector, ...args) {
return fork(function*() {
const tasks = {};
while (true) {
const action = yield take(patternOrChannel);
const key = yield call(keySelector, action);
if (!(tasks[key] && tasks[key].isRunning())) {
tasks[key] = yield fork(worker, ...args, action);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment