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

49 lines
1.2 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;
use Amp\Listener;
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) {
$listener = new Listener($stream);
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
});