Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Solve memory leak in Promise::fromObservable #198

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions src/React/Promise.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,32 @@ public static function rejected($exception): ReactPromise
*/
public static function fromObservable(ObservableInterface $observable, Deferred $deferred = null): ReactPromise
{
$subscription = null;
$promise = new ReactPromise(static function ($resolve, $reject) use (&$subscription, $observable) {
$value = null;
$subscription = $observable->subscribe(
static function ($v) use (&$value) {
$value = $v;
},
static function ($error) use ($reject) {
$reject($error);
},
static function () use ($resolve, &$value) {
$resolve($value);
}
);

$d = $deferred ?: new Deferred(function () use (&$subscription) {
}, static function () use (&$subscription) {
$subscription->dispose();
});

$value = null;
if ($deferred === null) {
return $promise;
}

$subscription = $observable->subscribe(
function ($v) use (&$value) {
$value = $v;
},
function ($error) use ($d) {
$d->reject($error);
},
function () use ($d, &$value) {
$d->resolve($value);
}
);
$promise->done([$deferred, 'resolve'], [$deferred, 'reject']);

return $d->promise();
return $deferred->promise();
}

/**
Expand Down
28 changes: 28 additions & 0 deletions test/Rx/Functional/React/PromiseFromObservableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Rx\Functional\React;

use Exception;
use React\Promise\Deferred;
use Rx\Functional\FunctionalTestCase;
use Rx\Observable;
use Rx\React\Promise;
Expand Down Expand Up @@ -49,4 +50,31 @@ function ($error) {
$this->assertEquals($error, new Exception("some error"));
});
}

/**
* @test
*/
public function promise_no_memory_leak()
{
gc_collect_cycles();

$source = Observable::of(42);

Promise::fromObservable($source)->done();

$this->assertSame(0, gc_collect_cycles());
}
/**
* @test
*/
public function promise_no_memory_leak_deferred()
{
gc_collect_cycles();

$source = Observable::of(42);

Promise::fromObservable($source, new Deferred())->done();

$this->assertSame(0, gc_collect_cycles());
}
}