Skip to content

Cancellation

Charles Demers edited this page Aug 21, 2024 · 2 revisions

Cancellation

Houston tasks can be canceled either explicitly (by calling one of the cancel methods on a task or task instance) or implicitly (based on how the task is configured).

Implicit Cancelation via Task Modifiers

Generally speaking, it is much better to configure your tasks properly (via Task Modifiers) such that they'll be implicitly/automatically canceled at the right time, but there are still some cases where explicit cancelation is the only option.

Explicit Cancelation

There are two ways to explicitly cancel a task:

  1. Call task.cancelAll() on the Task object — this will cancel all running or enqueued Task Instances for that task.
  2. Call taskInstance.cancel() on a Task Instance (the object returned from a prior call to task.perform())

Example

Tip: You can also use the runningTasksCount property to get the current number of running task instances for a given task, e.g. {myTask.runningTasksCount}

import { useState } from 'react';
import { useTask, timeout } from '@mirego/houston';

export default function TestComponent() {
  const [count, setCount] = useState(0);
  const [mostRecent, setMostRecent] = useState(null);

  const myTask = useTask(function* () {
    try {
      setCount((count) => count + 1);
      yield timeout(100_000);
    } finally {
      // finally blocks always get called,
      // even when the task is being canceled

      setCount((count) => count - 1);
    }
  });

  const performTask = () => {
    const taskInstance = myTask.perform();
    setMostRecent(taskInstance);
  }

  const cancelAll = () => {
    myTask.cancelAll();
  }

  const cancelMostRecent = () => {
    mostRecent?.cancel();
  }

  return (
    <div>
      <p>Running tasks: {count}</p>

      <button onClick={performTask} type="button">Perform Task</button>

      {!!count && (
        <button onClick={cancelAll} type="button">Cancel All</button>
      )}

      {mostRecent.isRunning && (
        <button onClick={cancelMostRecent} type="button">Cancel Most Recent</button>
      )}
    </div>
  );
}
Clone this wiki locally