1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 05:11:42 +01:00
amp/example/postponed.php
Aaron Piotrowski aa7b76e842 Add awaitable/coroutine-aware loop functions
These functions mirror the standard loop methods, but run returned Generators as coroutines and invoke rethrow() on returned awaitables.
2016-08-02 12:48:32 -05:00

51 lines
1.3 KiB
PHP

#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Amp\Coroutine;
use Amp\Observable;
use Amp\Observer;
use Amp\Pause;
use Amp\Postponed;
use Amp\Loop\NativeLoop;
Amp\execute(function () {
try {
$postponed = new Postponed;
Amp\defer(function () use ($postponed) {
// Observer emits all values at once.
$postponed->emit(1);
$postponed->emit(2);
$postponed->emit(3);
$postponed->emit(4);
$postponed->emit(5);
$postponed->emit(6);
$postponed->emit(7);
$postponed->emit(8);
$postponed->emit(9);
$postponed->emit(10);
$postponed->resolve(11);
});
$observable = $postponed->getObservable();
$generator = function (Observable $observable) {
$observer = new Observer($observable);
while (yield $observer->next()) {
printf("Observable emitted %d\n", $observer->getCurrent());
yield new Pause(100); // Observer consumption takes 100 ms.
}
printf("Observable result %d\n", $observer->getResult());
};
yield new Coroutine($generator($observable));
} catch (\Exception $exception) {
printf("Exception: %s\n", $exception);
}
}, $loop = new NativeLoop());