Skip to main content

use_task

Function use_task 

Source
pub fn use_task<T, E, Fut, F>(fetch: F) -> UseTask<T>
where T: Send + Sync + 'static, E: Error + Send + Sync + 'static, Fut: Future<Output = Result<T, E>> + Send + 'static, F: Fn() -> Fut + 'static,
Expand description

The heavy-work idiom: AsyncValue state, use_task (the blessed load/compute helper), UseTask handle, and spawn_blocking (the CPU-bound entry point) — Frust’s counterpart to Flutter’s compute()/FutureBuilder, with explicit cancellation on component teardown. spawn_blocking joins the existing spawn/spawn_local routing pair (async IO / UI-thread !Send / one-off CPU work). App crates need no new dependency: this is the whole heavy-work surface. See frust_reactive::task for the threading contract. Runs a fetch, wiring a heavy-work idiom around it.

Called from Component::init/build under the component’s Owner. It immediately starts a first fetch and returns a UseTask<T> to read the AsyncValue<T> state and to restart it.

  • T is the loaded value type (Send + Sync — it moves from a background thread to the UI thread, and lives in a thread-safe signal).
  • E is any std::error::Error the fetch may fail with (tokio’s JoinError qualifies, so || async { spawn_blocking(f).await } works directly).

See the module docs for the full threading/cancellation contract.

§Decision: hand-rolled vs AsyncDerived

reactive_graph 0.2 ships AsyncDerived (research §9), which this could wrap for a signal-driven restart. It is deliberately not used here: AsyncDerived re-runs when a tracked signal it reads changes, whereas use_task’s contract is an imperative first-load + explicit restart (the pull-to-refresh / retry shape), and its cancellation story is the leptos one the research refuted as non-explicit. Hand-rolling keeps all three guarantees visible in one place — background AbortHandle in on_cleanup, coordinator abort via spawn_local_scoped_with_cancellation, and last-write-wins by generation. A future AsyncDerived-backed signal-driven variant can live alongside this without changing it (a documented Future Enhancement in the plan).