phasync
Swerve / subscribe

Method

Swerve::subscribe

Receive what is published to $topic from now on.

Description#

public static Swerve::subscribe(
    string $topic,
    float $maxLag = 30.0,
    ?float $heartbeat = null
): Subscription

The subscription exists once this returns, not from the first iteration. It ends when its last reference goes, and its loop when the process drains; see Subscription. A subscriber falling more than $maxLag seconds behind gets a SubscriberLagException from the loop. With $heartbeat, the loop also gets null after that many seconds without a message: for a keep-alive.

Parameters#

$topic string
What Swerve::publish sent to
$maxLag float = 30.0
Seconds a message may wait before this subscriber reads it
$heartbeat ?float = null
Seconds without a message after which the loop yields null; null for never

Return values#

Iterate over it to receive the messages Subscription

Errors / Exceptions#

ExceptionWhen
InvalidArgumentExceptionFor a topic starting with "\0"

Examples#

Example 1What a subscriber receives for each kind of value
use Swerve\Swerve;
use Swerve\Util\SealedObject;

phasync::run(function () {
    $subscription = Swerve::subscribe('news');

    Swerve::publish('news', 'a string stays a string');
    Swerve::publish('news', ['a', 'list']);
    Swerve::publish('news', ['title' => 'An object', 'tags' => ['x', 'y']]);

    foreach ($subscription as $message) {
        echo get_debug_type($message), ': ', json_encode($message), "\n";
        if ($message instanceof SealedObject) {
            echo "title: $message->title\n";
            break;
        }
    }
});
Output
string: "a string stays a string"
array: ["a","list"]
Swerve\Util\SealedObject: {"title":"An object","tags":["x","y"]}
title: An object
Example 2A heartbeat for keep-alives
use Swerve\Swerve;

phasync::run(function () {
    phasync::go(function () {
        phasync::sleep(0.5);
        Swerve::publish('quiet', 'finally');
    });

    // null after each 0.2 s without a message: time for a keep-alive
    foreach (Swerve::subscribe('quiet', heartbeat: 0.2) as $message) {
        if (null === $message) {
            echo "keep-alive\n";
            continue;
        }
        echo "message: $message\n";
        break;
    }
});
Output
keep-alive
keep-alive
message: finally
Example 3
foreach (Swerve::subscribe('chat') as $message) {
    echo $message->text, "\n";   // an object arrives as a read-only SealedObject
}

See also#