1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 08:59:46 +01:00
amp/examples/pipeline/async-generator.php

42 lines
1.4 KiB
PHP
Raw Normal View History

2020-05-13 17:15:21 +02:00
#!/usr/bin/env php
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Amp\AsyncGenerator;
use Amp\Delayed;
2020-09-25 05:14:58 +02:00
use function Amp\await;
use function Amp\delay;
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
try {
/** @psalm-var AsyncGenerator<int, int, int> $generator */
$generator = new AsyncGenerator(function (): \Generator {
$value = yield 0;
$value = yield await(new Delayed(500, $value));
$value = yield $value;
$value = yield await(new Delayed(300, $value));
$value = yield $value;
$value = yield $value;
$value = yield await(new Delayed(1000, $value));
$value = yield $value;
$value = yield $value;
$value = yield await(new Delayed(600, $value));
return $value;
});
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
// Use AsyncGenerator::continue() to get the first emitted value.
if (null !== $value = $generator->continue()) {
\printf("Async Generator yielded %d\n", $value);
2020-09-25 05:14:58 +02:00
// Use AsyncGenerator::send() to send values into the generator and get the next emitted value.
while (null !== $value = $generator->send($value + 1)) {
\printf("Async Generator yielded %d\n", $value);
delay(100); // Listener consumption takes 100 ms.
2020-05-13 17:15:21 +02:00
}
}
2020-09-25 05:14:58 +02:00
\printf("Async Generator returned %d\n", $generator->getReturn());
} catch (\Exception $exception) {
\printf("Exception: %s\n", (string) $exception);
}