phasync
phasync / service

Method

phasync::service

Starts $fn as a service: a coroutine of no frame, in the root scope, which outlives the code that started it, and returns it.

Description#

public static phasync::service(
    callable $fn,
    mixed ...$args
): Fiber

A service is for one coroutine that serves many others and is started on first use, such as a connection manager. It belongs to no run(): no run() waits for it, and it runs while the outermost run() does. When the outermost run() has no coroutine left, it cancels its services and returns once they have ended, so write a service to be started again by the next use. It runs in the root scope (Scope::getRootScope()) whatever scope starts it, and phasync::frame throws inside it. A failure nobody awaits goes to the outermost run().

Parameters#

$fn callable
The service
...$args mixed
Passed to $fn

Return values#

The service's coroutine Fiber

Errors / Exceptions#

ExceptionWhen
LogicExceptionOutside a coroutine

Examples#

Example 1
phasync::run(function () {
    phasync::service(function () {
        phasync::sleep(10);   // cancelled when the run has nothing else to do
    });
    phasync::sleep(0.1);
    echo "main ends\n";
});
// run() returns after 0.1 seconds

See also#

  • phasync::goStarts $fn as a coroutine in the current frame and scope, and returns it, without waiting for it.
  • phasync::runRuns $fn and returns its result once it and every coroutine started inside it have ended.