2016-05-24 11:47:14 -05:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp;
|
|
|
|
|
2016-05-26 18:20:05 -05:00
|
|
|
final class Emitter implements Observable {
|
2016-06-01 11:19:19 -05:00
|
|
|
use Internal\Producer;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable(callable $emit): \Generator $emitter
|
|
|
|
*/
|
|
|
|
public function __construct(callable $emitter) {
|
|
|
|
$this->init();
|
|
|
|
|
2016-08-11 13:33:51 -05:00
|
|
|
if (PHP_VERSION_ID >= 70100) {
|
|
|
|
$emit = \Closure::fromCallable([$this, 'emit']);
|
|
|
|
} else {
|
|
|
|
$emit = function ($value) {
|
|
|
|
return $this->emit($value);
|
|
|
|
};
|
|
|
|
}
|
2016-06-01 11:19:19 -05:00
|
|
|
|
|
|
|
$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);
|
|
|
|
});
|
2016-05-24 11:47:14 -05:00
|
|
|
}
|
|
|
|
}
|