async-interop / event-loop

An event loop interface for interoperability in PHP.
MIT License
169 stars 9 forks source link

Reuse current loop with execute #144

Closed trowski closed 7 years ago

trowski commented 7 years ago

In the spirit of @davidwdan's PR #142, this PR allows the creation of loop events outside an execute context, however it still allows stacking of event loops and provides for consistent testing environments. The model here is inspired by @WyriHaximus's comment, allowing for both the React-style and Amp-style of creating events in the event loop.

With these changes both of the models below work as expected.

// React-style
Loop::defer(function () {
    echo '1' . PHP_EOL;
});

Loop::delay(1000, function () {
    echo '2' . PHP_EOL;
});

Loop::delay(2000, function () {
    echo '3' . PHP_EOL;
});

Loop::execute();
// Amp-style
Loop::execute(function () {
    Loop::defer(function () {
        echo '1' . PHP_EOL;
    });

    Loop::delay(1000, function () {
        echo '2' . PHP_EOL;
    });

    Loop::delay(2000, function () {
        echo '3' . PHP_EOL;
    });
});

Both will output:

1
2
3

Summary of Changes

kelunik commented 7 years ago

I don't think changing the behavior depending on whether an event has been created before Loop::execute or not is a good idea.

trowski commented 7 years ago

@kelunik The current behavior preserves the state of Loop before Loop::execute() is invoked (updated changes summary to make this clear). However, I considered leaving the driver that was created as the active driver after Loop::execute() returns. I'd like to hear more feedback on this point.

trowski commented 7 years ago

Closing in favor of @bwoebi's proposal in this comment.