# Channels

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

<a id="delivery"></a>

## 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.

```rust
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.
```

> 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.

<a id="effects"></a>

## Own delivery with an effect

Register view-owned channels during [effect setup](/docs/effects), 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.

**Without macros (View trait)**

```rust
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))
    }
}
```

**With macros**

```rust
use refract::prelude::*;
use std::rc::Rc;

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

#[view]
fn result_panel(
    cx: &mut ViewContext<'_>,
    path: String,
    start: StartLoad,
) -> impl View {
    #[state]
    let status: String = "Loading…".into();
    let output = cx.read(&status);

    #[effect(id = "load", deps = path.clone(), captures(path, start, status))]
    let load = |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()
    };

    text(output)
}
```

> `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.

<a id="platforms"></a>

## 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.

| Platform | Operation and delivery |
| --- | --- |
| Native | The sender is `Send + Sync`. Move or clone it into a worker thread or an async task; Winit wakes the UI loop for delivery. |
| Browser async | Keep the sender on the main thread and send from an async completion callback. The web host schedules a later flush. |
| Web Worker | Use `postMessage` to cross the Worker boundary. Decode the result on the main thread, then submit it through the sender. |

```rust
#[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.");
            }
        }
    });
}
```

> 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.

<a id="reactivity"></a>

## 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.

<a id="shared-models"></a>

## 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`.

```rust
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()
});
```

> This excerpt uses the `Profile` model from [Reactivity](/docs/reactivity#environment-object) and an application-defined `start_profile_load` function that accepts `MessageSender<String>`.

<a id="admission"></a>

## 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.

| Result | Meaning | Producer 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. |

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

<a id="hosts"></a>

## 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](/docs/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.
