Menu

Reference / Async

SelectCase

finalclass
final class SelectCase

One arm of a select().

Build it with SelectCase::recv() or SelectCase::send(). A bare Channel in the case list is also accepted, as shorthand for SelectCase::recv($ch).

Example

use Async\SelectCase;
use function Async\async;
use function Async\channel;
use function Async\delay;
use function Async\select;
use function Async\selectNow;
use function Async\selectWithin;
use function Async\spawn;

async(function () {
    $fast = channel();
    $slow = channel();

    spawn(function () use ($fast) { delay(0.01); $fast->send("from fast"); });
    spawn(function () use ($slow) { delay(0.05); $slow->send("from slow"); });

    // A bare channel is shorthand for a receive case.
    $r = select([$slow, $fast]);
    echo "case {$r->index}: {$r->value}\n";

    // Nothing is ready right now.
    var_dump(selectNow([$fast]));

    // A deadline: null when it expires first.
    var_dump(selectWithin(0.01, [$fast]));

    // The other value is still on its way.
    $r = select([$slow]);
    echo $r->value, "\n";

    // A send arm completes when a receiver (or buffer space) is available.
    $out = channel(1);
    $r = select([SelectCase::send($out, 7)]);
    echo $r->isSend ? "sent " : "received ", $out->recv(), "\n";
});

Output

case 1: from fast
NULL
NULL
from slow
sent 7

See also: select

Constants

RECV0Kind of a receive arm.
SEND1Kind of a send arm.

Methods

__construct()Build a case from its parts; prefer recv() and send().
recv()A case that completes when a value can be received from $ch (or $ch is closed).
send()A case that completes when $value can be sent to $ch.

__construct()#source

function __construct(public int $kind, public Channel $channel, public mixed $value)

Build a case from its parts; prefer recv() and send().

Parameters

$kind int
SelectCase::RECV or SelectCase::SEND
$channel Channel
the channel to receive from or send to
$value mixed
the value to send; ignored for a receive

recv()#source

static function recv(Channel $ch): SelectCase

A case that completes when a value can be received from $ch (or $ch is closed).

Parameters

$ch Channel
the channel to receive from

Returns

SelectCase โ€” the receive arm

send()#source

static function send(Channel $ch, mixed $value): SelectCase

A case that completes when $value can be sent to $ch.

Sending to a closed channel makes select() throw ChannelClosedException.

Parameters

$ch Channel
the channel to send to
$value mixed
the value to send

Returns

SelectCase โ€” the send arm

View source