PHP code example of leocavalcante / swoole-futures

1. Go to this page and download the library: Download leocavalcante/swoole-futures library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

leocavalcante / swoole-futures example snippets


$future = Futures\async(fn() => 1);
$result = $future->await(); // 1

$slow_rand = function (): int {
    Co::sleep(3);
    return rand(1, 100);
};

$n1 = Futures\async($slow_rand);
$n2 = Futures\async($slow_rand);
$n3 = Futures\async($slow_rand);

$n = Futures\join([$n1, $n2, $n3]);

print_r($n->await());

use Swoole\Coroutine\Http\Client;

$site1 = Futures\async(function() {
    $client = new Client('www.google.com', 443, true);
    $client->get('/');
    return $client->body;
});

$site2 = Futures\async(function() {
    $client = new Client('www.swoole.co.uk', 443, true);
    $client->get('/');
    return $client->body;
});

$site3 = Futures\async(function() {
    $client = new Client('leocavalcante.dev', 443, true);
    $client->get('/');
    return $client->body;
});

$first_to_load = Futures\race([$site1, $site2, $site3]);

echo $first_to_load;

$list = [1, 2, 3];
$multiply = fn(int $a) => fn(int $b) => $a * $b;
$double = $multiply(2);

$doubles = Futures\join(Futures\async_map($list, $double))->await();

print_r($doubles);

use function Futures\async;

$future = async(fn() => 2)
    ->then(fn(int $i) => async(fn() => $i + 3))
    ->then(fn(int $i) => async(fn() => $i * 4))
    ->then(fn(int $i) => async(fn() => $i - 5));

echo $future->await(); // 15

$stream = Futures\stream()
    ->map(fn($val) => $val + 1)
    ->filter(fn($val) => $val % 2 === 0)
    ->map(fn($val) => $val * 2)
    ->listen(fn($val) => print("$val\n")); // 4 8 12 16 20

foreach (range(0, 9) as $n) {
    $stream->sink($n);
}