phasync
Coordination and limits / Event

Class

Event

A list of listeners that are called when the event is triggered.

Introduction#

Listeners are called in the order they were added, in the coroutine that triggers the event, one at a time: a slow listener delays the trigger. A listener that throws stops the trigger: the exception reaches the caller of trigger() and the listeners after it are not called.

Class synopsis#

final class Event {
    /* Methods */
    public Event::trigger(mixed ...$args): void
    public Event::listen(Closure ...$listeners): void
    public Event::once(Closure ...$listeners): void
    public Event::off(Closure ...$listeners): void
    public Event::hasListeners(): bool
}

Methods#

MethodDescription
triggerCalls the listeners with $args, then the once() listeners, which are forgotten after that.
listenCalls $listeners every time the event triggers.
onceCalls $listeners the next time the event triggers, and not after.
offRemoves $listeners, whether they were added with listen() or once().
hasListenersReturns true if any listener is registered, with listen() or once().

Examples#

Example 1
$onMessage = new phasync\Util\Event();
$onMessage->listen(function (string $data, bool $binary) {
    echo "got $data\n";
});
$onMessage->once(fn () => print("first message only\n"));

$onMessage->trigger('hello', false);   // got hello, then: first message only
$onMessage->trigger('again', false);   // got again

See also#

  • Event::listenCalls $listeners every time the event triggers.
  • Event::triggerCalls the listeners with $args, then the once() listeners, which are forgotten after that.