1
0
mirror of https://github.com/danog/amp.git synced 2024-12-04 10:28:01 +01:00
amp/examples/streams/emitter.php

49 lines
1.3 KiB
PHP
Raw Normal View History

2016-05-24 18:47:14 +02:00
#!/usr/bin/env php
<?php
require __DIR__ . '/../../vendor/autoload.php';
2016-05-24 18:47:14 +02:00
use Amp\Coroutine;
use Amp\Emitter;
2017-04-13 18:20:46 +02:00
use Amp\StreamIterator;
use Amp\Pause;
use Amp\Stream;
use Amp\Loop;
Loop::run(function () {
2016-05-24 18:47:14 +02:00
try {
2017-01-04 02:10:27 +01:00
$emitter = new Emitter;
Loop::defer(function () use ($emitter) {
// Listener emits all values at once.
$emitter->emit(1);
$emitter->emit(2);
$emitter->emit(3);
$emitter->emit(4);
$emitter->emit(5);
$emitter->emit(6);
$emitter->emit(7);
$emitter->emit(8);
$emitter->emit(9);
$emitter->emit(10);
$emitter->resolve(11);
2016-05-27 22:44:01 +02:00
});
2017-01-04 02:10:27 +01:00
$stream = $emitter->stream();
2016-05-27 22:44:01 +02:00
2017-01-04 02:10:27 +01:00
$generator = function (Stream $stream) {
2017-04-13 18:20:46 +02:00
$listener = new StreamIterator($stream);
2017-01-04 02:10:27 +01:00
while (yield $listener->advance()) {
printf("Stream emitted %d\n", $listener->getCurrent());
yield new Pause(100); // Listener consumption takes 100 ms.
2016-05-27 01:20:05 +02:00
}
2017-01-04 02:10:27 +01:00
printf("Stream result %d\n", $listener->getResult());
2016-05-30 06:49:44 +02:00
};
2017-01-04 02:10:27 +01:00
yield new Coroutine($generator($stream));
} catch (\Throwable $exception) {
2016-05-24 18:47:14 +02:00
printf("Exception: %s\n", $exception);
}
2017-03-12 19:47:08 +01:00
});