Created
December 8, 2016 13:04
-
-
Save tomenden/a600115fe0549836e85b5503fe3cca84 to your computer and use it in GitHub Desktop.
Debounced channel
This file contains 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
//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