Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created May 16, 2023 15:12
Show Gist options
  • Save cowboyd/c702660ed5dd31f52272f8005f6b4212 to your computer and use it in GitHub Desktop.
Save cowboyd/c702660ed5dd31f52272f8005f6b4212 to your computer and use it in GitHub Desktop.
Explicit Drop vs Implicit drop.
export const takeLatest = (patternOrChannel, saga, ...args) => fork(function*() {
let lastTask
while (true) {
const action = yield* take(patternOrChannel)
if (lastTask) {
yield cancel(lastTask) // cancel is no-op if the task has already terminated
}
lastTask = yield* fork(saga, ...args.concat(action))
}
})
// this is the only helper that needs to change. Because `take` will see every match, even while handling logic is running
// we need to explicitly drop.
export const takeLeading = (patternOrChannel, saga, ...args) => fork(function*() {
// if we are actively handling an action, don't fork anything new.
let active = false;
while (true) {
const action = yield take(patternOrChannel);
if (!active) {
yield* fork(function*() {
try {
active = true;
yield* call(saga, ...args.concat(action));
} finally {
active = false;
}
});
}
}
});
export const takeEvery = (patternOrChannel, saga, ...args) => fork(function*() {
while (true) {
const action = yield* take(patternOrChannel)
yield* fork(saga, ...args.concat(action))
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment