1
0
mirror of https://github.com/danog/amp.git synced 2024-12-12 09:29:45 +01:00
amp/examples/streams/producer.php

45 lines
1.2 KiB
PHP
Raw Normal View History

2017-01-04 02:10:27 +01:00
#!/usr/bin/env php
<?php
require __DIR__ . '/../../vendor/autoload.php';
2017-01-04 02:10:27 +01:00
use Amp\Coroutine;
use Amp\Delayed;
use Amp\Loop;
use Amp\Producer;
use Amp\Stream;
use Amp\StreamIterator;
Loop::run(function () {
2017-01-04 02:10:27 +01:00
try {
$producer = new Producer(function (callable $emit) {
yield $emit(1);
yield $emit(new Delayed(500, 2));
2017-01-04 02:10:27 +01:00
yield $emit(3);
yield $emit(new Delayed(300, 4));
2017-01-04 02:10:27 +01:00
yield $emit(5);
yield $emit(6);
yield $emit(new Delayed(1000, 7));
2017-01-04 02:10:27 +01:00
yield $emit(8);
yield $emit(9);
yield $emit(new Delayed(600, 10));
2017-01-04 02:10:27 +01:00
return 11;
});
$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 Delayed(100); // Listener consumption takes 100 ms.
2017-01-04 02:10:27 +01:00
}
printf("Stream result %d\n", $listener->getResult());
};
yield new Coroutine($generator($producer));
} catch (\Exception $exception) {
printf("Exception: %s\n", $exception);
}
});