Skip to content

Instantly share code, notes, and snippets.

@tomenden
Created December 8, 2016 13:04
Show Gist options
  • Save tomenden/a600115fe0549836e85b5503fe3cca84 to your computer and use it in GitHub Desktop.
Save tomenden/a600115fe0549836e85b5503fe3cca84 to your computer and use it in GitHub Desktop.
Debounced channel
//usage example:
function* watchChangeAction() {
const changeActionChannel = yield actionChannel(actionTypes.CHANGE);
const requestChannel = yield call(debouncedChannel, 300, changeActionChannel);
// handleRequest will be called with the debounced actions
yield fork(handleRequest, requestChannel)
}
export function* debouncedChannel(ms, originalChannel) {
const newChannel = yield call(channel);
yield spawn(debounceAction, ms, originalChannel, newChannel);
return newChannel;
}
function* debounceAction(ms, originalChannel, targetChannel) {
while(true) {
let didEnoughTimePass = false;
let action = yield take(originalChannel);
while(!didEnoughTimePass) {
didEnoughTimePass = yield call(function*() {
const {anotherAction, enoughTimeHasPassed} = yield race({
anotherAction: take(originalChannel),
enoughTimeHasPassed: delay(ms).then(() => true)
});
if (enoughTimeHasPassed) {
return true;
} else {
action = anotherAction;
return false;
}
});
}
// once enough time has passed
yield put(targetChannel, action);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment