Background work
Run CPU-heavy and blocking work on worker threads, get the results back to the UI thread, and consume streams.
A UI task can wait without cost, but any real work it does delays the frame. Run CPU-heavy work and blocking calls on a worker thread, then bring the result back to the UI thread, where signals and views can be updated.
Choose where work runs
| Operation | Runs on | May use signals and views | Cancellation |
|---|---|---|---|
spawn / spawn_local | UI thread | yes | its scope, or Task::cancel |
background(future) | background executor | no | the work continues; a cancelled caller discards the result |
blocking(closure) | a worker that may block | no | the work continues; a cancelled caller discards the result |
ui().post(closure) | UI thread, at the next flush | yes | none |
All four are in the prelude.
Run an async operation on a worker
Await background from a UI task. Only the future passed to background moves to the worker;
the code after the await runs on the UI thread again.
view! {
control(on:click = move |_| {
spawn(async move {
loading.set(true);
let rows = background(async { fetch_rows().await }).await;
items.set(rows);
loading.set(false);
});
}) {"Reload"}
}The future and its output must be Send + 'static. The future must not read signals, use node
handles or touch the document. Read what it needs on the UI thread and move plain data in:
let id = selected.get();
let detail = background(async move { load_detail(id).await }).await;A signal read on a worker does not register a dependency, so the same rule applies inside
AsyncDerived and Action.
Awaiting a background result panics if the work panicked, or if the executor shut down before it
finished.
Run blocking code
Use blocking for synchronous work: parsing a file, decoding an image, calling a synchronous
database driver.
spawn(async move {
let report = blocking(move || parse_report(bytes)).await;
parsed.set(Some(report));
});Do not put a blocking call inside background(async { … }). An async executor runs many futures
on a few threads; blocking tells it that this work will not yield.
Post to the UI thread
ui() returns a Ui handle for the current UI thread. It is Send + Clone, so you can move it
into a worker thread or into a callback from a foreign library. Call ui() on the UI thread.
let ui = ui();
std::thread::spawn(move || {
for step in 0..=100 {
do_one_step(step);
ui.post(move || progress.set(step));
}
});post returns immediately. The closure runs at the start of the next flush, before UI tasks are
polled, and the post requests that frame.
Use Ui::run when worker code needs a value from the UI thread before it can continue:
let ui = ui();
background(async move {
let selected_id = ui.run(move || selected.get_untracked()).await;
fetch_detail(selected_id).await
})
.await;impl Ui {
pub fn post(&self, f: impl FnOnce() + Send + 'static);
pub fn run<T: Send + 'static>(
&self,
f: impl FnOnce() -> T + Send + 'static,
) -> impl Future<Output = T> + Send;
}A signal with thread-safe storage can be written from another thread, but do not rely on it. Reads
there do not subscribe, writes run outside any frame, and the first LocalStorage value in the
code path panics. Post a closure instead.
Discard stale results
Unmounting a component cancels its UI tasks. Work already running on a worker is not stopped; its result is discarded because nothing awaits it any more.
While the component stays mounted, nothing rejects an outdated result for you. After the await,
check that the request is still current:
let wanted = page.get_untracked();
let loaded = background(async move { fetch_page(wanted).await }).await;
if page.get_untracked() == wanted {
rows.set(loaded);
}Do the same for search input, route parameters, selection, and any value that can change while
work is pending. examples/async.rs in the zgui repository shows the full pattern, with a Cancel
button and a progress bar written from a plain thread.
Consume a stream
zgui::reactive::spawn_stream calls a closure on the UI thread for every item:
use zgui::reactive::spawn_stream;
spawn_stream(events, move |event| {
latest.set(Some(event));
});signal_from_stream keeps only the latest item, starting from an initial value:
use zgui::reactive::signal_from_stream;
let status = signal_from_stream(Status::Offline, status_updates);Both run the stream as a scoped UI task: it stops when the stream ends or the scope is disposed.
Neither needs a runtime: futures channels and Tokio's sync channels both work as they are. For
Tokio receivers, zgui::tokio has
ready-made helpers.
The default thread pool
Without the tokio feature, zgui starts its own pool on the first background or blocking
call. The pool:
- has at most four threads (fewer on smaller machines);
- has no I/O reactor, so Tokio timers, sockets and files do not work in it;
- runs
blockingwork on the same threads asbackgroundfutures, so four long blocking calls stall every other background task.
If you need a reactor, a separate blocking pool or more threads, install Tokio; see Tokio integration.
with_style_threads and with_layout_threads on app() size the style and layout pools. They do
not affect background or blocking.