phasync
Scopes and frames / Examples

Scopes and frames

Examples

Every example of this topic, with its output.

phasync::onScopeChange#

Example 1
$locales = new WeakMap();   // per Scope
phasync::onScopeChange(function (Scope $new) use ($locales) {
    Locale::setDefault($locales[$new] ?? 'en');
});

phasync::frame#

Example 1
phasync::run(function () {
    phasync::frame()->setTimeout(1.0);   // this run(), and every coroutine started inside it
});

Frame#

Example 1
phasync::run(function () {
    phasync::frame()->setTimeout(2.0);   // the whole run, its coroutines included
    phasync::go(fn () => fetch('a'));
    phasync::go(fn () => fetch('b'));
});   // throws phasync\TimeoutException after 2 seconds

Frame::cancel#

Example 1
phasync::run(function () {
    phasync::go(fn () => phasync::sleep(10));
    phasync::go(fn () => phasync::sleep(10));
    phasync::frame()->cancel();   // returns: the main coroutine is in the frame
    phasync::sleep(1);            // throws phasync\CancelledException
});

Frame::setTimeout#

Example 1
phasync::run(function () {
    phasync::frame()->setTimeout(0.5);
    phasync::sleep(10);
});   // throws phasync\TimeoutException after 0.5 seconds

Frame::requestCancellation#

Example 1
phasync::run(function () {
    $frame = phasync::frame();
    phasync::go(function () use ($frame) {
        while (!$frame->isCancellationRequested()) {
            phasync::sleep(0.01);   // one tick
        }
    });
    phasync::sleep(0.1);
    $frame->requestCancellation();   // the loop ends after its current tick
});

Frame::isCancellationRequested#

Example 1
while (!phasync::frame()->isCancellationRequested()) {
    $world->step();
    phasync::sleep(1 / 60);
}

Frame::setExceptionHandler#

Example 1
phasync::run(function () use ($logger) {
    phasync::frame()->setExceptionHandler(fn (Throwable $e) => $logger->error($e->getMessage()));
    phasync::go(fn () => throw new RuntimeException('lost'));   // logged; run() goes on
});