Blog>
Snippets

Implementing Task Cancellation

Provides an example of cancelling a running saga task using the `cancel` effect, useful in scenarios like race conditions or debouncing user input.
import { take, fork, cancel, call } from 'redux-saga/effects';

function* backgroundTask() {
  // Simulated background work
  while(true) {
    // do something
  }
}

function* watchStartBackgroundTask() {
  while(true) {
    yield take('START_TASK');
    // Fork a new task on each START_TASK action
    const bgTask = yield fork(backgroundTask);
    // Wait for the stop action
    yield take('STOP_TASK');
    // Cancel the background task
    yield cancel(bgTask);
  }
}
This code snippet shows how to implement task cancellation in Redux-Saga. A background task is initiated by the 'START_TASK' action and runs indefinitely until a 'STOP_TASK' action is received, upon which the task is cancelled.