Blog>
Snippets

Task Cancellation with `take` and `cancel`

Illustrate how to start a task with `fork`, then use `take` to listen for a cancellation action and `cancel` to terminate the task.
import { take, fork, cancel } from 'redux-saga/effects';

function* startTask() {
  // Task that might need cancellation
}

function* watchAndCancel() {
  // Start the task
  const task = yield fork(startTask);

  // Wait for the cancel action
  yield take('CANCEL_TASK');

  // Cancel the task
  yield cancel(task);
}
This code snippet starts by importing the necessary effects from the redux-saga/effects. It defines a generator function `startTask` which represents the task that might need to be canceled later. The `watchAndCancel` generator function is responsible for starting the `startTask` function with `fork`, allowing it to execute in the background. It then waits for a 'CANCEL_TASK' action using `take`. Upon receiving this action, it proceeds to cancel the previously started task with `cancel`, effectively terminating its execution.