2015-05-18 20:25:33 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp;
|
|
|
|
|
2015-06-15 19:17:27 +02:00
|
|
|
class PromiseStream {
|
2015-05-18 20:25:33 +02:00
|
|
|
private $promisors;
|
|
|
|
private $index = 0;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param \Amp\Promise $watchedPromise
|
|
|
|
*/
|
|
|
|
public function __construct(Promise $watchedPromise) {
|
2015-05-19 06:21:33 +02:00
|
|
|
$this->promisors[] = new Deferred;
|
2015-05-18 20:25:33 +02:00
|
|
|
$watchedPromise->watch(function($data) {
|
2015-05-19 06:21:33 +02:00
|
|
|
$this->promisors[$this->index + 1] = new Deferred;
|
2015-05-18 20:25:33 +02:00
|
|
|
$this->promisors[$this->index++]->succeed($data);
|
|
|
|
});
|
|
|
|
$watchedPromise->when(function($error, $result) {
|
|
|
|
if ($error) {
|
|
|
|
$this->promisors[$this->index]->fail($error);
|
2015-05-19 22:20:53 +02:00
|
|
|
} else {
|
|
|
|
$this->promisors[$this->index]->succeed();
|
2015-05-18 20:25:33 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a stream of promises that may be iteratively yielded to await resolution
|
|
|
|
*
|
|
|
|
* NOTE: Only values sent to Promise::update() will be streamed. The final resolution
|
2015-06-15 19:17:27 +02:00
|
|
|
* value of the promise is not sent to the stream -- instead, the final promise value
|
|
|
|
* is NULL. If the Promise is failed that failure will resolve the stream's current Promise.
|
2015-05-18 20:25:33 +02:00
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
|
|
|
public function stream() {
|
|
|
|
while ($this->promisors) {
|
|
|
|
$key = key($this->promisors);
|
|
|
|
yield $this->promisors[$key]->promise();
|
2015-05-23 22:44:31 +02:00
|
|
|
unset($this->promisors[$key]);
|
2015-05-18 20:25:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|