Skip to content

channel ​

channel creates a typed channel and returns its two owned endpoints as a tuple.

Signaturechannel<T>(capacity?: usize): [Sender<T>, Receiver<T>]

capacity is optional: omit it for an unbounded channel, or pass a usize to bound the number of buffered values, Sender<T>.send/trySend wait for (or reject on) room once a bounded channel is full. Sender<T>.send(value: T): Promise<void> waits for room and delivers value, rejecting with channel is closed once every Receiver<T> has been dropped; Sender<T>.trySend(value: T): boolean never waits, returning true once accepted or false if the channel is full or closed. Receiver<T>.recv(): Promise<T?> waits for the next message, resolving to None once every Sender<T> has been dropped and nothing remains buffered; Receiver<T>.tryRecv(): T? never waits, returning the next buffered message or None if there isn't one yet. Receiver<T>.close(): void closes the channel, send/trySend start failing, while recv/tryRecv still drain whatever was already buffered before settling to None. Like Promise<T> and JoinHandle<T>, Sender<T>/Receiver<T> are native types and never need to be imported.

Channel payloads are restricted to the same subset Promise<T> itself supports: string, arrays of Copy elements, and Copy scalars, not arbitrary interfaces.

A Sender<T>/Receiver<T> moved into a spawn task is consumed there, the same way any other owned value is: capturing one twice, say, into two separate tasks, is a compile-time move error, so a single producer or consumer per endpoint is the shape to reach for. The example below moves tx into one spawned worker that streams a result back for each host as soon as it resolves, letting main process results as they arrive instead of waiting for every lookup to finish the way Promise.all would, see the Playground page under Tooling for why this example does not run there:

tyrus
import { NetError, resolve } from "tyrus:net";
import { Sender, channel, spawn } from "tyrus:task";

async function lookupAllInto(tx: Sender<string>, hosts: string[]): Promise<void> {
    for (let i: usize = 0; i < hosts.length; i = i + 1) {
        try {
            const addresses: string[] = await resolve(hosts[i], 2_000);
            await tx.send(`${hosts[i]}: ${addresses.length} address(es)`);
        } catch (error: NetError) {
            await tx.send(`${hosts[i]}: lookup failed`);
        }
    }
}

async function main(): Promise<void> {
    const [tx, rx] = channel<string>();
    // The worker streams each host's result back through the channel as
    // soon as it resolves, instead of making the caller wait for every
    // lookup to finish the way `Promise.all` would.
    const worker = spawn(async (): Promise<void> => await lookupAllInto(tx, ["example.com", "localhost"]));

    for (let i = 0; i < 2; i = i + 1) {
        const result = await rx.recv();
        print(result ?? "no result");
    }
    rx.close();
    await worker.join();
}

A capacity of 0 is a compile error (E3035): a channel with no room holds nothing, so every send would wait for a recv that has nowhere to take the value from. Omit the argument to use the default capacity.