1
0
mirror of https://github.com/danog/amp.git synced 2024-11-26 20:15:00 +01:00
amp/lib/Emitter.php

47 lines
1.2 KiB
PHP
Raw Normal View History

2016-08-18 05:25:54 +02:00
<?php declare(strict_types = 1);
2016-08-16 06:46:26 +02:00
2016-05-24 18:47:14 +02:00
namespace Amp;
2016-08-16 09:28:47 +02:00
use Interop\Async\{ Awaitable, Loop };
2016-05-27 01:20:05 +02:00
final class Emitter implements Observable {
use Internal\Producer;
/**
2016-08-16 09:28:47 +02:00
* @param callable(callable(mixed $value): Awaitable $emit): \Generator $emitter
*
* @throws \Error Thrown if the callable does not return a Generator.
*/
public function __construct(callable $emitter) {
if (PHP_VERSION_ID >= 70100) {
$emit = \Closure::fromCallable([$this, 'emit']);
} else {
$emit = function ($value): Awaitable {
return $this->emit($value);
};
}
$result = $emitter($emit);
if (!$result instanceof \Generator) {
2016-08-11 21:35:58 +02:00
throw new \Error("The callable did not return a Generator");
}
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-05-24 18:47:14 +02:00
}
}