Skip to content

Cancelling Work

How-to Guide1 min read
Edit page

You will stop work that is no longer wanted — abandoned searches, closed panels, superseded polls — using Quoin’s cancellation toolkit, which behaves identically on all five adapters.

Prerequisites: familiarity with spawning tasks (Loading Async Data).

CancellationToken is cloneable and cheap. The most direct pattern checks it inside a loop:

let token = CancellationToken::new();
executor.spawn({
let token = token.clone();
async move {
while !token.is_cancelled() {
do_work().await;
}
cleanup().await;
}
});
// Later, from another task or UI event:
token.cancel();

Cancellation is cooperative: nothing preempts your future. It stops at its next suspension point, so long computations between .awaits delay it.

token.cancelled() returns a future that resolves when the token fires; into_cancelled() gives an owned variant. Use them to select between completion and shutdown:

tokio::select! {
result = work() => handle(result),
_ = token.cancelled() => shutdown().await,
}

run_until_cancelled resolves with Some(output) when the wrapped future finishes first, or None when the token wins:

let value = token.run_until_cancelled(work()).await;
match value {
Some(result) => apply(result),
None => /* cancelled */,
}

Long-lived screens create child tokens that cancel together with their parent but also cancel independently:

let parent = CancellationToken::new();
let per_request = parent.child_token(); // cancels with the parent
// Cancelling per_request leaves parent untouched.
// Cancelling parent also cancels per_request.

This models UI lifetimes: one parent token per view, one child per in-flight request.

guard() returns an RAII guard that cancels the token when dropped — the “cancel when this scope exits” pattern:

let token = CancellationToken::new();
let _guard = token.guard(); // token.cancel() runs when _guard drops

Dropping a join handle cancels the task; that is structured concurrency by default. When you genuinely want fire-and-forget, call detach() explicitly so the task runs to completion:

let handle = executor.spawn(log_flusher());
handle.detach(); // survives; drop(handle) would have cancelled it