Documentation / Fundamentals

Channels

Deliver async and background results to reactive state on web and native.

Send results to the UI thread

Create a typed channel with rt.channel(callback). It returns a MessageSender<T> for the operation and a MessageSubscription that owns the receive callback’s registration. Keep the subscription alive until you no longer want results.

The callback stays on the UI thread, so it can capture State, Binding, and Rc models. Only owned messages cross the native thread boundary. Call sender.try_send(value) from your operation; the host wakes and delivers the result during a later flush.

Register a callback
let (sender, subscription) = rt.channel(move |rt, result: String| {
    status.set_if_changed(rt, result);
});

// Give sender to the operation. Keep subscription in effect cleanup.
i

This excerpt assumes a runtime and a String binding named status. Sending never executes the receive callback inline. Success means queued, not applied or painted.

Own delivery with an effect

Register view-owned channels during effect setup, after a successful commit. Return subscription.into_cleanup() to keep the channel open until cleanup. This transfers ownership into a boxed cleanup callback; running or dropping that callback closes delivery. Discarded view preparations then start no work, and replacing the effect or unmounting closes delivery.

Use the request’s inputs as explicit dependencies. In this example, changing path closes the previous channel before starting its replacement. The injected start function launches the operation and sends a Result<String, String> when it finishes.

results.rs
use refract::prelude::*;
use std::rc::Rc;

type LoadResult = Result<String, String>;
type StartLoad = Rc<dyn Fn(String, MessageSender<LoadResult>)>;

struct ResultPanel {
    path: String,
    start: StartLoad,
}

impl View for ResultPanel {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let status = cx.state("status", || "Loading…".to_owned());
        let output = cx.read(&status);
        let path = self.path.clone();
        let start = self.start.clone();

        cx.effect("load", path.clone(), move |rt| {
            status.set_if_changed(rt, "Loading…".into());
            let status = status.clone();
            let (sender, subscription) = rt.channel(move |rt, result: LoadResult| {
                let value = result.unwrap_or_else(|error| format!("Failed: {error}"));
                status.set_if_changed(rt, value);
            });
            start(path.clone(), sender);
            subscription.into_cleanup()
        });

        Ok(text(output))
    }
}
i

into_cleanup() packages subscription ownership for effect cleanup. Dropping the subscription discards undelivered messages and rejects late results; it does not cancel the request or computation itself. If the operation supports cancellation, close the subscription first, then cancel it in the same cleanup closure. Concurrent requests within one effect still need request IDs if only the newest result should apply.

Run the operation on each platform

Channels handle result delivery. Your HTTP client, file API, or executor still performs the operation. Shared views can call one application function, with platform implementations selected by #[cfg(...)] in the same module; a separate crate is not required.

The native implementation below starts a file read on a thread and sends its result. An HTTP task uses the same pattern after awaiting and decoding its response. Keep blocking work out of effect setup and receive callbacks.

PlatformOperation and delivery
NativeThe sender is Send + Sync. Move or clone it into a worker thread or an async task; Winit wakes the UI loop for delivery.
Browser asyncKeep the sender on the main thread and send from an async completion callback. The web host schedules a later flush.
Web WorkerUse postMessage to cross the Worker boundary. Decode the result on the main thread, then submit it through the sender.
Native operation · with refract::prelude::* imported
#[cfg(not(target_arch = "wasm32"))]
fn start_file_load(
    path: String,
    sender: MessageSender<Result<String, String>>,
) {
    std::thread::spawn(move || {
        let result = std::fs::read_to_string(path)
            .map_err(|error| error.to_string());
        match sender.try_send(result) {
            Ok(()) | Err(SendError::Closed(_)) => {}
            Err(SendError::Full(_)) => {
                eprintln!("Result queue is full; retry the request.");
            }
        }
    });
}
i

Messages must be Send + 'static on both targets. Browser objects need conversion to owned application data. A Rust sender is not transferable to a separate Web Worker, and a browser async task alone does not move CPU-heavy work off the main thread.

Keep graph updates incremental

Receive callbacks write through the same State and Binding methods as event handlers. The host drains a snapshot of up to 128 messages in one graph mutation batch before preparing views. Derived attributes settle at the end of that batch, and only affected observers become dirty.

Receiving a message does not itself invalidate a view. Use set_if_changed to skip equal values, and read bindings through cx.read during view evaluation to subscribe. Derived values can remain stale inside a receive callback until the batch settles.

Messages submitted during delivery wait for a later drain. Remaining work schedules another flush, allowing the host to commit and yield between batches.

Update an environment object

A receive callback can capture the Rc model returned by cx.object() or #[environment_object]. Update its graph-backed fields normally. Descendant views that read those bindings react without intermediate components forwarding results.

Own the channel in a provider-level effect for shared loading, or a consumer effect for work that should stop when that view disappears. Ordinary fields and RefCell values do not notify the graph; keep observable values in State or Binding.

Inside View::body
let profile = cx.object::<Profile>()?;

cx.effect("load-profile", (), move |rt| {
    let profile = profile.clone();
    let (sender, subscription) = rt.channel(move |rt, name: String| {
        profile.name.set_if_changed(rt, name);
    });
    start_profile_load(sender);
    subscription.into_cleanup()
});
i

This excerpt uses the Profile model from Reactivity and an application-defined start_profile_load function that accepts MessageSender<String>.

Handle admission and closure

All channels in a runtime share a queue of up to 1,024 pending messages. try_send does not wait for capacity. Both error variants return the original value, allowing the producer to choose whether to retain it, retry later, or report a failure.

Messages are FIFO by admission order across channels in the runtime. Concurrent senders have no predetermined relative order, and there is no global FIFO ordering against input events or existing host update queues. Capacity limits message count, not payload bytes.

ResultMeaningProducer behavior
Ok(())Accepted for later delivery.Continue. Closure before execution can still discard this message.
SendError::Full(value)The shared inbox is full.Throttle, retain for a later retry, or report the failure. Never spin on the UI thread.
SendError::Closed(value)The subscription or runtime has closed.Stop sending; this channel cannot deliver again.
i

Senders are weak: they do not keep the app or callback alive. App disposal closes every channel, including subscriptions held outside mounted effects.

Custom hosts and tests

Native and web hosts install Runtime::set_message_waker before effect setup and call Runtime::drain_messages before preparation. Custom hosts need the same integration. The message waker schedules a later flush; it must not execute graph work inline. This notification is separate from the graph waker that runs after observer invalidation.

TestHost::flush drains one bounded batch automatically. Its return value reports whether a view update committed, not whether messages were delivered. For a larger burst, use app.runtime().has_pending_messages() to decide whether another flush is needed. Finish or synchronize the producer before asserting the final result.

Read Async Work for inbox ownership, notification, batching, and lifecycle internals.

Raw runtime users can call drain_messages directly. It returns the number of callbacks invoked, and nested drains do nothing. close_channels closes all registrations, clears queued messages, and removes the message waker; hosts call it on disposal.