Channel::close

(PHP 8.6+, True Async 1.0)

public Channel::close(): void

Closes the channel. After closing:

Calling close() again on an already closed channel does not cause errors.

Examples

Example #1 Closing a channel after sending data

<?php

use Async\Channel;

$channel = new Channel(10);

spawn(function() use ($channel) {
    for ($i = 0; $i < 5; $i++) {
        $channel->send($i);
    }
    $channel->close(); // signal to the receiver that no more data will come
});

spawn(function() use ($channel) {
    foreach ($channel as $value) {
        echo "Received: $value\n";
    }
    // foreach terminates after closing and draining the buffer
    echo "Channel exhausted\n";
});

Example #2 Handling closure by waiting coroutines

<?php

use Async\Channel;

$channel = new Channel();

spawn(function() use ($channel) {
    try {
        $channel->send('data'); // waiting for a receiver
    } catch (\Async\ChannelException $e) {
        echo "Channel closed: {$e->getMessage()}\n";
    }
});

spawn(function() use ($channel) {
    delay(100); // short delay
    $channel->close(); // unblocks the sender with an exception
});

See also