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

45 lines
1.2 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';
use Amp\Coroutine;
use Amp\Emitter;
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;
Amp\execute(function () {
2016-05-24 11:47:14 -05:00
try {
$emitter = new Emitter(function (callable $emit) {
yield $emit(1);
yield $emit(new Pause(500, 2));
yield $emit(3);
yield $emit(new Pause(300, 4));
yield $emit(5);
yield $emit(6);
yield $emit(new Pause(1000, 7));
yield $emit(8);
yield $emit(9);
yield $emit(new Pause(600, 10));
2016-08-11 14:35:58 -05:00
return 11;
2016-05-27 15:44:01 -05:00
});
2016-05-29 23:49:44 -05:00
$generator = function (Observable $observable) {
$observer = new Observer($observable);
2016-05-27 15:44:01 -05:00
while (yield $observer->advance()) {
2016-05-29 23:49:44 -05:00
printf("Observable emitted %d\n", $observer->getCurrent());
2016-05-30 10:24:03 -05:00
yield new Pause(100); // Observer consumption takes 100 ms.
2016-05-26 18:20:05 -05:00
}
2016-05-30 10:24:03 -05:00
printf("Observable result %d\n", $observer->getResult());
2016-05-29 23:49:44 -05:00
};
yield new Coroutine($generator($emitter));
2016-05-29 23:49:44 -05:00
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-11-14 13:59:21 -06:00
});