Blog>
Snippets

Cleanup with finally

Illustrates how to handle cleanup operations in a saga task using a 'finally' block, ensuring resources are released or state is reset when tasks are cancelled.
import { take, put, call, fork, cancel, cancelled } from 'redux-saga/effects';
function* backgroundTask() {
  try {
    // Simulate a long-running task
    while (true) {
      yield call(delay, 1000);
      // Perform some action
      yield put({type: 'TASK_TICK'});
    }
  } finally {
    // Check if the saga was cancelled
    if (yield cancelled()) {
      // Perform cleanup operations
      yield put({type: 'TASK_CANCELLED'});
    }
  }
}
This code snippet defines a backgroundTask saga that runs indefinitely until it's manually cancelled. In the finally block, it checks if the saga was cancelled using `yield cancelled()`. If true, it then performs any necessary cleanup operations, like dispatching a TASK_CANCELLED action to reset the state or release resources.
import { delay } from 'redux-saga';
function* rootSaga() {
  const bgTask = yield fork(backgroundTask);
  yield take('STOP_BACKGROUND_SYNC');
  yield cancel(bgTask);
}
This code snippet demonstrates the usage of the previous backgroundTask within a rootSaga. It forks the backgroundTask, waits for a 'STOP_BACKGROUND_SYNC' action, and then cancels the task. Cancelling the task triggers the finally block within backgroundTask, allowing it to execute its cleanup logic.