1
0
mirror of https://github.com/danog/amp.git synced 2024-11-30 04:29:08 +01:00
amp/lib/Emitter.php
Aaron Piotrowski c4e9a19095 Rename Emitter to Producer; add new Emitter class
Emitter uses a coroutine to emit values. Updated examples.
2016-06-01 11:19:19 -05:00

40 lines
908 B
PHP

<?php
namespace Amp;
final class Emitter implements Observable {
use Internal\Producer;
/**
* @param callable(callable $emit): \Generator $emitter
*/
public function __construct(callable $emitter) {
$this->init();
/**
* @param mixed $value
*
* @return \Interop\Async\Awaitable
*/
$emit = function ($value = null) {
return $this->emit($value);
};
$result = $emitter($emit);
if (!$result instanceof \Generator) {
throw new \LogicException("The callable did not return a Generator");
}
$coroutine = new Coroutine($result);
$coroutine->when(function ($exception, $value) {
if ($exception) {
$this->fail($exception);
return;
}
$this->resolve($value);
});
}
}