1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 21:31:18 +01:00
amp/example/emitter.php

50 lines
1.3 KiB
PHP
Raw Normal View History

2016-05-24 11:47:14 -05:00
#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
2016-05-29 23:49:44 -05:00
use Amp\Observable;
use Amp\Observer;
2016-05-24 11:47:14 -05:00
use Amp\Pause;
2016-05-26 18:20:05 -05:00
use Amp\Postponed;
2016-05-24 11:47:14 -05:00
use Amp\Loop\NativeLoop;
2016-05-26 18:20:05 -05:00
use Interop\Async\Loop;
2016-05-24 11:47:14 -05:00
2016-05-29 23:49:44 -05:00
Loop::execute(Amp\coroutine(function () {
2016-05-24 11:47:14 -05:00
try {
2016-05-26 18:20:05 -05:00
$postponed = new Postponed;
2016-05-27 15:44:01 -05:00
Loop::defer(function () use ($postponed) {
2016-05-29 12:07:21 -05:00
$postponed->emit(1);
$postponed->emit(2);
$postponed->emit(3);
$postponed->emit(4);
2016-05-27 15:44:01 -05:00
$postponed->emit(5);
$postponed->emit(6);
$postponed->emit(7);
2016-05-29 12:07:21 -05:00
$postponed->emit(8);
2016-05-27 15:44:01 -05:00
$postponed->emit(9);
$postponed->emit(10);
2016-05-29 11:35:09 -05:00
$postponed->resolve(11);
2016-05-27 15:44:01 -05:00
});
$observable = $postponed->getObservable();
2016-05-29 23:49:44 -05:00
$generator = function (Observable $observable) {
$observer = new Observer($observable);
2016-05-27 15:44:01 -05:00
2016-05-29 23:49:44 -05:00
while (yield $observer->isValid()) {
printf("Observable emitted %d\n", $observer->getCurrent());
yield new Pause(100);
2016-05-26 18:20:05 -05:00
}
2016-05-29 23:49:44 -05:00
printf("Observable result %d\n", $observer->getReturn());
};
yield new \Amp\Coroutine($generator($observable));
2016-05-26 18:20:05 -05:00
} catch (\Exception $exception) {
2016-05-24 11:47:14 -05:00
printf("Exception: %s\n", $exception);
}
2016-05-29 23:49:44 -05:00
}), $loop = new NativeLoop());