Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Last active November 16, 2023 20:42
Show Gist options
  • Save ourmaninamsterdam/da5af76fcaec4d425ccb7a19db7739e5 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/da5af76fcaec4d425ccb7a19db7739e5 to your computer and use it in GitHub Desktop.
redux-saga - Running long tasks then cancelling
import { createStore, applyMiddleware } from "redux";
import { all, fork, delay } from "typed-redux-saga";
import createSagaMiddleware from "redux-saga";
const sagaMiddleware = createSagaMiddleware();
const store = createStore(() => undefined, applyMiddleware(sagaMiddleware));
const task = sagaMiddleware.run(rootSaga);
function* taskSaga() {
console.log("taskSaga - start");
const fooTask = yield* fork(longTaskSaga, "Foo", 500);
const barTask = yield* fork(longTaskSaga, "Bar", 500);
const sagaTimeLimit = 2000;
while (true) {
console.log(`taskSaga - running for ${sagaTimeLimit}ms`);
yield* delay(sagaTimeLimit, true);
console.log("taskSaga - cancelling running tasks");
if (fooTask.isRunning()) {
console.log(`taskSaga - cancelling fooTask`);
fooTask.cancel();
}
if (barTask.isRunning()) {
console.log(`taskSaga - cancelling barTask`);
barTask.cancel();
}
break;
}
console.log("taskSaga - done");
}
function* logSaga() {
while(true) {
yield* delay(1000, true);
console.log('Beep');
}
}
function* longTaskSaga(label: string, maxDelay: number) {
yield* fork(tasks, `${label}::TaskGroup1`, 5, maxDelay);
yield* fork(tasks, `${label}::TaskGroup2`, 2, maxDelay);
}
function* tasks(label: string, maxCount: number, maxDelay: number) {
let count = 0;
let totalTime = 0;
while (count < maxCount) {
const timeDelay = Math.random() * maxDelay;
yield delay(timeDelay);
console.log(`${label}::${count + 1} in ${timeDelay}`);
totalTime += timeDelay;
count++;
}
console.log(`Completed ${count} of ${label} tasks in ${totalTime}`);
}
export default function* rootSaga() {
setTimeout(() => {
console.log('Cancelling root saga');
task.cancel()
}, 6000);
yield all([taskSaga(), logSaga()]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment