Initial commit
This commit is contained in:
22
examples/basic_example.php
Normal file
22
examples/basic_example.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use JoopSchilder\React\Stream\NonBlockingInput\ReadableNonBlockingInputStream;
|
||||
use React\EventLoop\Factory;
|
||||
|
||||
require_once __DIR__ . '/../vendor/autoload.php';
|
||||
require_once __DIR__ . '/basic_example_classes.php';
|
||||
|
||||
/**
|
||||
* The input will have data available every second.
|
||||
* After 4 seconds have passed, it will generate an error.
|
||||
*/
|
||||
$input = new DemoNonBlockingInput();
|
||||
|
||||
$loop = Factory::create();
|
||||
$stream = new ReadableNonBlockingInputStream($input, $loop);
|
||||
$stream->on('data', fn() => print('m'));
|
||||
$stream->on('error', fn() => print('e'));
|
||||
$stream->on('close', fn() => print('c'));
|
||||
$loop->addPeriodicTimer(0.2, fn() => print('.'));
|
||||
$loop->run();
|
||||
|
||||
46
examples/basic_example_classes.php
Normal file
46
examples/basic_example_classes.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use JoopSchilder\React\Stream\NonBlockingInput\NonBlockingInputInterface;
|
||||
use JoopSchilder\React\Stream\NonBlockingInput\PayloadInterface;
|
||||
|
||||
final class DemoEmptyPayload implements PayloadInterface
|
||||
{
|
||||
}
|
||||
|
||||
final class DemoNonBlockingInput implements NonBlockingInputInterface
|
||||
{
|
||||
private const DATA_AVAILABLE_INTERVAL_S = 1.0;
|
||||
private const ERROR_AFTER_S = 4.0;
|
||||
|
||||
private float $lastEmission = 0;
|
||||
|
||||
private float $initialEmission = 0;
|
||||
|
||||
|
||||
public function open(): void
|
||||
{
|
||||
$this->initialEmission = microtime(true);
|
||||
}
|
||||
|
||||
|
||||
public function select(): ?PayloadInterface
|
||||
{
|
||||
$now = microtime(true);
|
||||
if ($now - $this->initialEmission > self::ERROR_AFTER_S) {
|
||||
throw new Exception('Oh no!');
|
||||
}
|
||||
if ($now - $this->lastEmission > self::DATA_AVAILABLE_INTERVAL_S) {
|
||||
$this->lastEmission = $now;
|
||||
|
||||
return new DemoEmptyPayload();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user