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
): SubscriptionThe 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::publishsent 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#
| Exception | When |
|---|---|
InvalidArgumentException | For a topic starting with "\0" |
Examples#
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 objectuse 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
foreach (Swerve::subscribe('chat') as $message) {
echo $message->text, "\n"; // an object arrives as a read-only SealedObject
}See also#
Swerve::publishSends the messagesOrderedChannelWhen every subscriber must see one common order