UI tasks and timers
Run futures on the UI thread, cancel them, show a placeholder while they load, and schedule timers and frame callbacks.
A UI task is a future that runs on the UI thread, so it can read and write signals directly. Use UI tasks to wait: for a response, a channel, or a timer. A timer runs a callback after a delay or on the next frame. Work that keeps the CPU busy or blocks a thread belongs on a worker instead; see Background work.
Spawn a task
use zgui::prelude::*;
#[component]
fn Answer() -> impl IntoView {
let answer = RwSignal::new(String::from("Waiting"));
spawn(async move {
answer.set(ask().await);
});
view! { text {{move || answer.get()}} }
}pub fn spawn(future: impl Future<Output = ()> + Send + 'static) -> Task;
pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> Task;Both queue the future on the UI thread. It first runs at the next reactive flush, not during the
call. The only difference is the bound: use spawn_local when the future holds a node handle, a
callback or another !Send value. The Send bound on spawn does not move the task to a worker.
Waiting in a UI task costs nothing. Working does: one slow poll delays the whole frame. Move long
CPU work and blocking calls to background or blocking.
Cancel a task
A task belongs to the scope it was spawned in: the component body, or the component a listener was written in. Disposing the scope cancels the task and immediately drops what it captured, so a component's tasks stop when it unmounts. Closing a window unmounts its view, which cancels every task in it.
When a component body rebuilds, the tasks from the previous run are cancelled before the new run starts.
To cancel a task earlier, keep the Task that spawn returns:
let current = RwSignal::new_local(None::<Task>);
let start = move || {
let task = spawn_local(async move {
load_editor_state().await;
});
current.set(Some(task));
};
let cancel = move || {
if let Some(task) = current.get_untracked() {
task.cancel();
}
current.set(None);
};impl Task {
pub fn cancel(&self);
pub fn is_finished(&self) -> bool; // finished or cancelled
}Dropping a Task does not cancel it, so spawn(async { … }); works as written. Keep the
handle only for a Cancel action or to check whether the task is done.
zgui::reactive::spawn_detached starts a task that outlives its scope, for work such as a final
save. It must not depend on state owned by that scope.
When the application ends, zgui polls the remaining tasks once more and then drops them. A detached task that is still waiting at that point does not finish.
Show a placeholder while loading
Await runs one future and builds a view from its output. Suspense and Transition show a
fallback while an Await below them is pending.
view! {
{Suspense::new(
|| AnyView::new(view! { label {"Loading…"} }),
|| AnyView::new(Await::new(load_profile(), |profile: Profile| {
AnyView::new(view! { label {{profile.name}} })
})),
)}
}| Type | Behavior |
|---|---|
Await | Renders nothing until the future resolves, then children(value). The output must be Clone. |
Suspense | Shows the fallback whenever anything below it is pending. |
Transition | Shows the fallback only before the first result; later loads keep the previous content. |
SuspenseContext | The pending-operation counter behind a boundary. |
An Await's task belongs to the scope that built it, so removing the view cancels the pending
future.
To make a boundary wait for work that does not use Await, call SuspenseContext::nearest() in
the component. Call expect_one() before the work starts and resolve_one() on the UI thread
when it ends.
Async values and actions
zgui::reactive (not the prelude) has three types for async state:
| Type | Use |
|---|---|
AsyncDerived<T> | An async value recomputed when the signals it reads change. Reads return None until the first result arrives. |
Action<I, O> | An operation started from an input, such as Save or Send. |
AsyncTransition | Waits for the async derived values read in one operation, keeping the previous values visible meanwhile. |
Read signals in the closure body, on the UI thread, and pass only plain data to background:
use zgui::reactive::AsyncDerived;
let detail = AsyncDerived::new(move || {
let id = selected.get(); // tracked, on the UI thread
background(async move { load_detail(id).await })
});A signal read inside the background future does not subscribe, so the value would never
recompute.
Run code after a delay
pub fn set_timeout(after: Duration, callback: impl FnOnce() + 'static) -> TimeoutHandle;
pub fn set_interval(every: Duration, callback: impl FnMut() + 'static) -> IntervalHandle;Call these in a component body. The timer is cancelled when its handle is dropped or when the
scope that created it is disposed, so store the handle for as long as the timer should live.
TimeoutHandle and IntervalHandle are at zgui::view.
use core::time::Duration;
use zgui::prelude::*;
use zgui::view::TimeoutHandle;
#[component]
fn Notice() -> impl IntoView {
let shown = RwSignal::new(true);
let timeout = StoredValue::new_local(Some(set_timeout(
Duration::from_secs(4),
move || shown.set(false),
)));
view! {
if move || shown.get() {
control(on:click = move |_| {
timeout.set_value(None); // cancel the pending timeout
shown.set(false);
}) {"Dismiss"}
}
}
}- Timers run on the window's clock, not the wall clock. Tests advance that clock by hand.
- A due callback runs at the start of a frame, before reactive work, so its writes show in that frame.
- An interval schedules its next run from the current time. After a long stall it does not fire the missed runs.
- Timers due at the same moment run in registration order.
- A timer runs only in the window that scheduled it. Closing that window discards its timers.
Start a timer from a listener
In a listener, use the window's Timers. Take it with Timers::current() in the component body
and move it into the listener. A timer created through Timers is not tied to a scope: only its
handle cancels it, so store the handle in the component.
#[component]
fn Tooltip() -> impl IntoView {
let open = RwSignal::new(false);
let timers = Timers::current().expect("the component is in a window");
let pending = StoredValue::new_local(None::<TimeoutHandle>);
view! {
box(
on:pointer_enter = move |_| {
pending.set_value(Some(timers.set_timeout(
Duration::from_millis(700),
move || open.set(true),
)));
},
on:pointer_leave = move |_| {
pending.set_value(None);
open.set(false);
},
) {"More information"}
}
}Replacing the stored handle cancels the previous timeout, so moving the pointer in and out quickly never opens the tooltip late.
Run work on the next frame
request_frame runs a callback once during the next frame and passes that frame's Timestamp.
Use it to drive an animation; use set_timeout for elapsed-time work.
pub fn request_frame(callback: impl FnOnce(Timestamp) + 'static) -> FrameHandle;While a request is pending, the window renders at the display's refresh rate. To run every frame, request again from inside the callback; the new request always waits for the next frame.
use zgui::view::FrameHandle;
use zgui::vocab::Timestamp;
fn step(
timers: Timers,
position: RwSignal<f32>,
last: Timestamp,
pending: StoredValue<Option<FrameHandle>, LocalStorage>,
) {
let next = timers.clone();
pending.set_value(Some(timers.request_frame(move |now| {
let dt = now.saturating_since(last).as_secs_f32();
position.update(|x| *x += dt * 120.0);
step(next, position, now, pending);
})));
}Compute motion from the timestamps. A slow frame then takes one larger step instead of slowing the animation down.
The free request_frame is cancelled by dropping its FrameHandle or by disposing its scope.
Timers::request_frame (for listeners) is cancelled only by its handle. A zero-length
set_timeout also runs on the next frame, but does not keep the window rendering at display rate.
How tasks are scheduled
| Rule | Consequence |
|---|---|
| Spawn on the UI thread. | Debug builds panic if spawn or spawn_local runs on another thread. |
| Tasks advance only during the flush. | A wake from any thread (worker, channel, timer) requests a frame. Many wakes before that frame cost one frame. With nothing ready, the event loop stays parked. |
| Posted closures run before tasks. | At the start of a flush, zgui runs closures sent with Ui::post, then polls ready tasks, so writes from both show in the same frame. |
| Writes settle in the same flush. | Effects woken by a task's signal writes run in the same flush, without an extra frame. |
| A task re-polled too often in one flush is deferred. | Past 32 polls (debug) or 8 (release) in one flush, zgui logs an error with the spawn site and resumes the task next frame. This almost always means a task writes a signal it depends on. |
| Panics are not caught. | A panicking task propagates to the frame loop. |