2016-12-29 21:09:49 +01:00
|
|
|
<?php
|
2016-08-16 06:46:26 +02:00
|
|
|
|
2016-05-24 18:47:14 +02:00
|
|
|
namespace Amp;
|
|
|
|
|
2016-08-30 01:29:21 +02:00
|
|
|
use Interop\Async\Loop;
|
2016-08-14 16:57:17 +02:00
|
|
|
|
2016-05-27 01:20:05 +02:00
|
|
|
final class Emitter implements Observable {
|
2016-08-30 17:22:10 +02:00
|
|
|
use CallableMaker, Internal\Producer;
|
2016-06-01 18:19:19 +02:00
|
|
|
|
|
|
|
/**
|
2016-11-14 20:59:21 +01:00
|
|
|
* @param callable(callable(mixed $value): Promise $emit): \Generator $emitter
|
2016-08-16 20:07:38 +02:00
|
|
|
*
|
|
|
|
* @throws \Error Thrown if the callable does not return a Generator.
|
2016-06-01 18:19:19 +02:00
|
|
|
*/
|
|
|
|
public function __construct(callable $emitter) {
|
2016-08-30 17:22:10 +02:00
|
|
|
$result = $emitter($this->callableFromInstanceMethod("emit"));
|
2016-06-01 18:19:19 +02:00
|
|
|
|
|
|
|
if (!$result instanceof \Generator) {
|
2016-08-11 21:35:58 +02:00
|
|
|
throw new \Error("The callable did not return a Generator");
|
2016-06-01 18:19:19 +02:00
|
|
|
}
|
2016-08-16 20:07:38 +02: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 18:19:19 +02:00
|
|
|
});
|
2016-05-24 18:47:14 +02:00
|
|
|
}
|
|
|
|
}
|