Scopes and frames
Examples
Every example of this topic, with its output.
phasync::onScopeChange#
$locales = new WeakMap(); // per Scope
phasync::onScopeChange(function (Scope $new) use ($locales) {
Locale::setDefault($locales[$new] ?? 'en');
});phasync::frame#
phasync::run(function () {
phasync::frame()->setTimeout(1.0); // this run(), and every coroutine started inside it
});Frame#
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 secondsFrame::cancel#
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#
phasync::run(function () {
phasync::frame()->setTimeout(0.5);
phasync::sleep(10);
}); // throws phasync\TimeoutException after 0.5 secondsFrame::requestCancellation#
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#
while (!phasync::frame()->isCancellationRequested()) {
$world->step();
phasync::sleep(1 / 60);
}Frame::setExceptionHandler#
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
});