Tasks
HuxerUI Task<T> is a lazy C++ coroutine type.
Launch top-level work through a scoped TaskScope so unmount cancels outstanding operations.
Define an asynchronous operation
Section titled “Define an asynchronous operation”Task<void> LoadProfile(State<std::string> status) { status = "Loading"; co_await Delay(std::chrono::milliseconds(250)); status = "Ready";}A task does not begin merely because its value was created. It begins when awaited or launched by an owning scope.
Launch from UI lifetime
Section titled “Launch from UI lifetime”[[huxerui::composable]]View LoadButton(State<std::string> status) { auto tasks = UseTaskScope(); return Button("Load").OnClick([tasks, status] { tasks.Launch(LoadProfile(status)); });}TaskScope::Launch accepts a Task<void> or a factory returning one and returns a TaskHandle.
The scope cancels all active handles when its component unmounts; explicit Cancel() is idempotent.
Capture State and service handles by value.
Update State directly in a synchronous UI event when changing a view or navigation value. The update schedules recomposition for a later frame. Launch a task when the operation actually awaits work. A retained inactive page keeps its scope and tasks alive, so pause nonessential polling through the page’s visibility policy.
Do not retain raw View objects or platform objects across suspension unless their API explicitly provides that lifetime.
Compose and handle failures
Section titled “Compose and handle failures”Tasks may await other HuxerUI tasks.
Delay resumes through the platform scheduler, and service operations such as HTTP and files return tasks that follow the same continuation model.
Exceptions propagate through co_await.
Catch failures at the boundary that can present a useful result, and make cancellation a normal control-flow outcome rather than a detached background exception.
Choose the owner before launching
Section titled “Choose the owner before launching”Create the TaskScope in the smallest scoped component that owns the result.
A page-level refresh belongs to the page scope; a row-level thumbnail load belongs to the keyed row scope.
Moving the scope higher keeps work alive longer, while moving it lower cancels work as soon as that feature leaves composition.
Keep the returned TaskHandle only when the user needs an explicit cancel or a newer request must supersede an older one.
Calling Cancel() more than once or after completion is safe.
Scope destruction remains the final backstop, so a forgotten handle does not detach the coroutine from UI lifetime.
For repeated requests, decide which result wins. Cancel the previous handle for “latest request wins,” or associate a generation/key with the request and ignore a stale completion. Do not let an older response overwrite newer controlled state merely because it completed later.
Understand suspension and state
Section titled “Understand suspension and state”The coroutine may resume after composition has run many times.
Captured State<T> and service handles are stable value handles; transient View values and mounted-node pointers are not.
Read request inputs before launch when one operation must use a snapshot, and read state after suspension only when the latest value is intentionally required.
Cancellation stops continuation of work owned by the HuxerUI execution, but a platform operation may still need time to release its native request. Do not use cancellation as a transaction rollback; commit external mutations only where the underlying service defines that guarantee.
Keep work off the composition path
Section titled “Keep work off the composition path”Composition declares current UI and must not block on I/O. Launch work from an event, lifecycle setup, activation handler, or another task. Update controlled state with the result so a later composition declares the new interface.
Do not detach raw coroutines that retain component state. See the Task API and the asynchronous HTTP and Files services.
Move CPU processing to a worker
Section titled “Move CPU processing to a worker”Await RunWorker(function, arguments...) for non-UI synchronous computation. It owns its callable/arguments and returns to the awaiting UI task after completion. Do not access State or platform UI from the worker; copy the input snapshot before launching and apply the result after awaiting.
Use WorkerSequence only when related operations must run serially, such as a decoder or ordered file transformation. It gives ordering rather than permanent thread affinity. Its leading stop token makes active cancellation cooperative.
TaskScope::Post is reserved for callbacks from external threads. HTTP, Files, Delay, and RunWorker continuations already execute in the correct task context. See the worker example.
Keep application work alive across windows
Section titled “Keep application work alive across windows”UseApplicationTaskScope belongs to the original Runtime and runs without UI frames. Obtain it during application installation or ordinary application-thread work. Its tasks survive window retirement and are canceled during application shutdown. It grants no background execution entitlement.
#include <huxerui/huxerui.h>#include <memory>
using namespace huxerui;
struct SyncModel { State<std::string> status{std::string{"Waiting"}};};
void InstallSync(ApplicationContext& context) { auto model = std::make_shared<SyncModel>(); context.Provide(model); UseApplicationTaskScope().Launch([model]() -> Task<void> { co_await Delay(std::chrono::milliseconds(200)); model->status = "Application task completed"; });}UseTaskScope remains the right owner for work useful only while a component is mounted. Neither scope permits State access from worker code. TaskScope::Post queues external callbacks and drops delivery after that scope closes; HuxerUI awaitables already restore their execution context.
For work that needs OS admission or background scheduling, use System tasks. An application-owned TaskScope lasts across windows while the process is alive.
Adapt a callback API
Section titled “Adapt a callback API”AwaitCallback retains a starter and supplies a copyable CallbackCompletion. This example wraps a library’s single-read contract instead of introducing another UI dispatcher:
#include <huxerui/huxerui.h>#include <exception>#include <functional>#include <memory>
using namespace huxerui;
struct SensorApi { virtual ~SensorApi() = default; virtual std::function<void()> Read( std::function<void(int)> success, std::function<void(std::exception_ptr)> failure) = 0;};
Task<int> ReadSensor(std::shared_ptr<SensorApi> sensor) { return AwaitCallback<int>([sensor](CallbackCompletion<int> completion) { return sensor->Read( [completion](int value) { completion.Complete(value); }, [completion](std::exception_ptr error) { completion.Fail(error); }); });}
Task<void> ShowReading(std::shared_ptr<SensorApi> sensor, State<std::string> label) { try { const int reading = co_await ReadSensor(sensor); label = std::to_string(reading); } catch (const std::exception& error) { label = error.what(); }}The library supplies the actual SensorApi implementation. Its returned cancellation action must not throw. The starter runs once when the lazy Task is awaited and must not block. Complete/Fail may run from another thread; the awaiting task resumes through its owning dispatcher and context, never inline before the starter returns.
Only the first completion/failure wins. Canceling a pending task invokes the cancellation action at most once and suppresses continuation; late callbacks are ignored. Cancellation after submission but before queued resumption can still suppress application code without invoking that action. Cancellation is not an unconditional cleanup callback.
Capture owned inputs. If startup throws after partially starting native work, clean it up in the adapter. If the native host closes while a task is still live, settle it with a suitable result or Fail; otherwise it can wait forever. See Tasks API for precise terminal and threading rules.

