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

41 lines
1.0 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\Loop;
2020-09-25 05:14:58 +02:00
use Amp\Pipeline;
2020-08-23 16:18:28 +02:00
use Amp\PipelineSource;
use function Amp\delay;
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
try {
/** @psalm-var PipelineSource<int> $source */
$source = new PipelineSource;
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
Loop::defer(function () use ($source): void {
// Source emits all values at once without awaiting back-pressure.
$source->emit(1);
$source->emit(2);
$source->emit(3);
$source->emit(4);
$source->emit(5);
$source->emit(6);
$source->emit(7);
$source->emit(8);
$source->emit(9);
$source->emit(10);
$source->complete();
});
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
$pipeline = $source->pipe();
2020-05-13 17:15:21 +02:00
2020-09-25 05:14:58 +02:00
// Use Amp\Pipeline\toIterator() to use a pipeline with foreach.
foreach (Pipeline\toIterator($pipeline) as $value) {
\printf("Pipeline source 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
} catch (\Throwable $exception) {
\printf("Exception: %s\n", (string) $exception);
}