2016-08-17 22:25:54 -05:00
|
|
|
<?php declare(strict_types = 1);
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-05-24 11:47:14 -05:00
|
|
|
namespace Amp;
|
|
|
|
|
2016-08-16 02:28:47 -05:00
|
|
|
use Interop\Async\{ Awaitable, Loop };
|
2016-08-14 16:57:17 +02:00
|
|
|
|
2016-05-26 18:20:05 -05:00
|
|
|
final class Emitter implements Observable {
|
2016-06-01 11:19:19 -05:00
|
|
|
use Internal\Producer;
|
|
|
|
|
|
|
|
/**
|
2016-08-16 02:28:47 -05:00
|
|
|
* @param callable(callable(mixed $value): Awaitable $emit): \Generator $emitter
|
2016-08-16 13:07:38 -05:00
|
|
|
*
|
|
|
|
* @throws \Error Thrown if the callable does not return a Generator.
|
2016-06-01 11:19:19 -05:00
|
|
|
*/
|
|
|
|
public function __construct(callable $emitter) {
|
2016-08-16 13:07:38 -05:00
|
|
|
if (PHP_VERSION_ID >= 70100) {
|
|
|
|
$emit = \Closure::fromCallable([$this, 'emit']);
|
|
|
|
} else {
|
|
|
|
$emit = function ($value): Awaitable {
|
|
|
|
return $this->emit($value);
|
|
|
|
};
|
|
|
|
}
|
2016-08-14 16:57:17 +02:00
|
|
|
|
2016-06-01 11:19:19 -05:00
|
|
|
$result = $emitter($emit);
|
|
|
|
|
|
|
|
if (!$result instanceof \Generator) {
|
2016-08-11 14:35:58 -05:00
|
|
|
throw new \Error("The callable did not return a Generator");
|
2016-06-01 11:19:19 -05:00
|
|
|
}
|
2016-08-16 13:07:38 -05:00
|
|
|
|
|
|
|
Loop::defer(function () use ($result) {
|
|
|
|
$coroutine = new Coroutine($result);
|
|
|
|
$coroutine->when(function ($exception, $value) {
|
|
|
|
if ($this->resolved) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($exception) {
|
|
|
|
$this->fail($exception);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->resolve($value);
|
|
|
|
});
|
2016-06-01 11:19:19 -05:00
|
|
|
});
|
2016-05-24 11:47:14 -05:00
|
|
|
}
|
|
|
|
}
|