Skip to content

Commit

Permalink
Merge pull request #13 from WyriHaximus/racecondition
Browse files Browse the repository at this point in the history
Fix race condition
  • Loading branch information
WyriHaximus authored Jan 26, 2019
2 parents 9c0f0e2 + 10af1eb commit 3ed8890
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/ObservableWhile.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ public function __construct(ObservableInterface $observable)
$this->queue = new \SplQueue();
$observable->subscribe(function ($item): void {
if ($this->deferred instanceof Deferred) {
$this->deferred->resolve($item);
$deferred = $this->deferred;
$this->deferred = null;
$deferred->resolve($item);

return;
}
Expand Down
52 changes: 52 additions & 0 deletions tests/RaceConditionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php declare(strict_types=1);

namespace WyriHaximus\Tests\Rx;

use ApiClients\Tools\TestUtilities\TestCase;
use React\EventLoop\Factory;
use Recoil\React\ReactKernel;
use Rx\Subject\Subject;
use Throwable;
use function WyriHaximus\Rx\observableWhile;

/**
* @internal
*/
final class RaceConditionTest extends TestCase
{
public function testRaceCondition(): void
{
$output = [];
$subject = new Subject();

$loop = Factory::create();
$recoil = ReactKernel::create($loop);
$recoil->setExceptionHandler(function (Throwable $error): void {
echo (string)$error;
});
$recoil->execute(function () use ($subject, &$output, $loop) {
$observableWhile = observableWhile($subject);
while ($i = (yield $observableWhile->get())) {
$i = $i();
$output[] = $i;
}
});
$loop->addTimer(0.5, function () use ($loop, $subject): void {
$loop->futureTick(function () use ($subject): void {
$subject->onNext(function () use ($subject) {
$subject->onNext(function () {
return 2;
});

return 1;
});
});
});
$loop->addTimer(1, function () use ($subject): void {
$subject->onCompleted();
});
$loop->run();

self::assertSame([1,2], $output);
}
}

0 comments on commit 3ed8890

Please sign in to comment.