Skip to content

Background tasks

Run slow work outside the coordinator and return typed results to component state.

On this page

Native input and painting run on the UI thread. Inrux serializes application handlers and state work on a coordinator. Slow handlers can still delay application updates, so move expensive work into the bounded task pool.

The task pattern

  1. Copy or move the required inputs into owned values.
  2. Submit work with Context::spawn_task and handle admission failure.
  3. Return a Result from the worker.
  4. Apply the typed outcome to component state in the completion callback.
rs
let request = state.name.clone();
match context.spawn_task(
    move |cancellation| {
        if cancellation.is_cancelled() {
            return Err("Cancelled".to_owned());
        }
        Ok::<_, String>(format!("Prepared {request}"))
    },
    |state, result, _context| {
        state.message = match result {
            Ok(message) => message,
            Err(error) => format!("Task failed: {error:?}"),
        };
    },
) {
    Ok(task) => state.task = Some(task),
    Err(error) => state.message = error.to_string(),
}

This fragment belongs in a handler whose State has String name/message fields and an optional TaskHandle field. The trivial worker illustrates ownership; it does not need a background thread for performance.

Cancellation and errors

Keep the returned TaskHandle if you want an explicit Cancel button. cancel() requests cooperative cancellation and prevents stale completion delivery. It cannot interrupt arbitrary blocking Rust code. For superseded requests, cancel the old task or track a request ID before applying results.

The current pool has two workers and 16 pending slots. Handle queue saturation. Worker failures and panics return typed task outcomes; do not silently turn them into success.

Use the Background playground implementation for a complete cancellable example. The separate threads do not guarantee that an application can never lag.

Inrux · Built with Nuxt Content, IPEX, and Akaza UI.