fromArray() public static method

Converts an array to an observable sequence
public static fromArray ( array $array ) : Rx\Observable\ArrayObservable
$array array
return Rx\Observable\ArrayObservable
コード例 #1
0
 public function commits() : ObservableInterface
 {
     return Promise::toObservable($this->getTransport()->request('repos/' . $this->slug() . '/builds'))->flatMap(function ($response) {
         return Observable::fromArray($response['commits']);
     })->map(function ($build) {
         return $this->getTransport()->getHydrator()->hydrate('Commit', $build);
     });
 }
コード例 #2
0
 /**
  * @return ObservableInterface
  */
 public function jobs() : ObservableInterface
 {
     return Promise::toObservable($this->getTransport()->request('builds/' . $this->id()))->flatMap(function ($response) {
         return Observable::fromArray($response['jobs']);
     })->map(function ($job) {
         return $this->getTransport()->getHydrator()->hydrate('Job', $job);
     });
 }
コード例 #3
0
ファイル: Job.php プロジェクト: WyriHaximus/php-travis-client
 /**
  * @return ObservableInterface
  */
 public function annotations() : ObservableInterface
 {
     return Promise::toObservable($this->getTransport()->request('jobs/' . $this->id() . '/annotations'))->flatMap(function ($response) {
         return Observable::fromArray($response['annotations']);
     })->map(function ($annotation) {
         return $this->getTransport()->getHydrator()->hydrate('Annotation', $annotation);
     });
 }
コード例 #4
0
ファイル: FromArrayTest.php プロジェクト: voryx/Rx.PHP
 /**
  * @test
  */
 public function fromArray_dispose()
 {
     $xs = Observable::fromArray(['foo', 'bar', 'baz']);
     $results = $this->scheduler->startWithDispose(function () use($xs) {
         return $xs;
     }, 202);
     $this->assertMessages([onNext(201, 'foo')], $results->getMessages());
 }
コード例 #5
0
ファイル: FunctionAwaitTest.php プロジェクト: RxPHP/RxAwait
 /**
  * @test
  */
 public function await_multiple()
 {
     $array = [1, 2, 3];
     $observable = Observable::fromArray($array);
     $generator = \Rx\await($observable);
     $result = [];
     foreach ($generator as $item) {
         $result[] = $item;
     }
     $this->assertEquals($array, $result);
     $this->assertEquals(count($result), 3);
 }
コード例 #6
0
ファイル: ch08-rx-defer.php プロジェクト: luijar/fp-php
function findSavingsAccountObs($userId)
{
    return Observable::just($userId)->skipWhile(function ($input) {
        return empty($input);
    })->map(function ($userId) {
        return User::find($userId);
    })->flatMap(function (User $user) {
        return Observable::fromArray(Account::query('user_id', $user->getId()));
    })->takeWhile(function (Account $account) {
        return $account->getType() === 'SAVINGS';
    });
}
コード例 #7
0
 /**
  * @param \Rx\ObservableInterface $observable
  * @param \Rx\ObserverInterface $observer
  * @param \Rx\SchedulerInterface $scheduler
  * @return \Rx\DisposableInterface
  */
 public function __invoke(ObservableInterface $observable, ObserverInterface $observer, SchedulerInterface $scheduler = null)
 {
     $buffer = "";
     return $observable->defaultIfEmpty(Observable::just(null))->concat(Observable::just($this->delimiter))->concatMap(function ($x) use(&$buffer) {
         if ($x === null || $buffer === null) {
             $buffer = null;
             return Observable::emptyObservable();
         }
         $items = explode($this->delimiter, $buffer . $x);
         $buffer = array_pop($items);
         return Observable::fromArray($items);
     })->subscribe($observer, $scheduler);
 }
コード例 #8
0
ファイル: distinctUntilChanged.php プロジェクト: ihor/RxPHP
<?php

require_once __DIR__ . '/../bootstrap.php';
$source = \Rx\Observable::fromArray([24, 42, 24, 24])->distinctUntilChanged();
$subscription = $source->subscribe($stdoutObserver);
//Next value: 24
//Next value: 42
//Next value: 24
//Complete!
コード例 #9
0
ファイル: min.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . "/../bootstrap.php";
/* Without comparer */
$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])->min();
$subscription = $source->subscribe($createStdoutObserver());
コード例 #10
0
ファイル: ch08-rx-db.php プロジェクト: luijar/fp-php
println('Example 3 - Just and Map');
\Rx\Observable::just(\Model\User::all())->map(function ($results) {
    return count($results);
})->subscribe($stdoutObserver());
println('Example 4 - Get all accounts of type SAVING');
\Rx\Observable::fromArray(\Model\Account::all())->filter(function (Account $account) {
    return $account->getType() === 'SAVINGS';
})->map(function (Account $savingsAccount) {
    return $savingsAccount->getBalance();
})->subscribe($stdoutObserver());
println('Withdraw 1000 from Luis SAVINGS account');
$id = 1;
Observable::just($id)->map(function ($userId) {
    return User::find($userId);
})->doOnNext(function (User $user) {
    printf("Found user: %s \n", $user->getEmail());
})->flatMap(function (User $user) {
    return Observable::fromArray(Account::query('user_id', $user->getId()));
})->takeWhile(function (Account $account) {
    return $account->getType() === 'SAVINGS';
})->doOnNext(function (Account $account) {
    printf("Found savings account. Current balance: %d \n", $account->getBalance());
})->map(function (Account $account) {
    return $account->withdraw(1000)->save();
})->subscribe(new Observer\CallbackObserver(function ($account) {
    printf("New account balance: %d \n", $account->getBalance());
}, function (Exception $ex) {
    print 'Error: ' . $ex->getMessage();
}, function () {
    print 'Completed!';
}));
コード例 #11
0
ファイル: distinctKey.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . '/../bootstrap.php';
$source = \Rx\Observable::fromArray([['id' => '42'], ['id' => '24'], ['id' => '42'], ['id' => '24']])->distinctKey(function ($x) {
    return $x['id'];
})->map(function ($x) {
    return $x['id'];
});
$subscription = $source->subscribe($stdoutObserver);
コード例 #12
0
<?php

require_once __DIR__ . '/../bootstrap.php';
$source = \Rx\Observable::fromArray([['id' => '24'], ['id' => '42'], ['id' => '24'], ['id' => '24']])->distinctUntilKeyChanged(function ($x) {
    return $x['id'];
})->map(function ($x) {
    return $x['id'];
});
$subscription = $source->subscribe($stdoutObserver);
コード例 #13
0
ファイル: stream_twitter.php プロジェクト: RxPHP/RxHttp
})->map(function ($tweet) {
    return json_decode($tweet);
});
$endTwitterStream = $allTweets->filter(function ($tweet) {
    return is_object($tweet);
})->filter(function ($tweet) {
    return trim($tweet->text) == 'exit();';
})->doOnNext(function ($twitter) {
    echo 'exit(); found, stopping...', PHP_EOL;
});
$usersTweets = $allTweets->filter(function ($tweet) {
    return isset($tweet->user->screen_name);
});
$tweets = $usersTweets->takeUntil($endTwitterStream);
$urls = $tweets->flatMap(function ($tweet) {
    return \Rx\Observable::fromArray($tweet->entities->urls);
});
$measurementsSubscription = $urls->filter(function ($url) {
    return substr($url->expanded_url, 0, 36) == 'https://atlas.ripe.net/measurements/';
})->map(function ($url) {
    return trim(substr($url->expanded_url, 36), '/');
})->flatMap(function ($id) {
    return \Rx\React\Http::get("https://atlas.ripe.net/api/v1/measurement/{$id}/");
})->map(function ($data) {
    return json_decode($data);
})->subscribeCallback(function ($json) {
    echo 'Measurement #', $json->msm_id, ' "', $json->description, '" had ', $json->participant_count, ' nodes involved', PHP_EOL;
}, function (\Rx\React\HttpResponseException $e) {
    echo "Error: ", $e->getMessage(), PHP_EOL;
}, function () {
    echo "complete", PHP_EOL;
コード例 #14
0
<?php

require_once __DIR__ . '/../bootstrap.php';
//With a result selector
$range = \Rx\Observable::fromArray(range(0, 4));
$source = $range->zip([$range->skip(1), $range->skip(2)], function ($s1, $s2, $s3) {
    return $s1 . ':' . $s2 . ':' . $s3;
});
$observer = $createStdoutObserver();
$subscription = $source->subscribe($createStdoutObserver());
コード例 #15
0
ファイル: retry.php プロジェクト: voryx/Rx.PHP
<?php

require_once __DIR__ . '/../bootstrap.php';
$count = 0;
$observable = \Rx\Observable::fromArray(range(1, 5))->flatMap(function ($x) use(&$count) {
    if (++$count < 2) {
        return new \Rx\Observable\ErrorObservable(new \Exception("Something"));
    }
    return new \Rx\Observable\ReturnObservable($x);
})->retry(3)->take(1);
$observable->subscribe($stdoutObserver);
コード例 #16
0
ファイル: demo.php プロジェクト: domraider/rxnet
<?php

use EventLoop\EventLoop;
use Rxnet\Observer\StdOutObserver;
use Rxnet\RabbitMq\RabbitMessage;
require __DIR__ . "/../../vendor/autoload.php";
$loop = EventLoop::getLoop();
$redis = new \Rxnet\Redis\Redis();
$redis->connect('localhost:6379')->doOnNext(function () {
    echo "Redis is connected\n";
})->subscribeCallback(function () use($redis, $loop) {
    // produce this array to my queue
    \Rx\Observable::fromArray(['coucou', 'hi'])->flatMap(function ($data) use($redis) {
        // add to set
        return $redis->sAdd('my_set', $data);
    })->doOnNext(function () {
        echo "Data added\n";
    })->flatMap(function () use($redis) {
        return $redis->sRandMember('my_set', 1);
    })->map(function ($data) {
        $data = $data[0];
        return $data;
    })->subscribeCallback(function ($data) use($redis) {
        echo "Read data {$data} add it to key\n";
        return $redis->set($data, 1);
    }, null, function () {
        // And close process
        EventLoop::getLoop()->stop();
    });
});
$loop->run();
コード例 #17
0
ファイル: demo.php プロジェクト: domraider/rxnet
<?php

use EventLoop\EventLoop;
use Rx\Observable;
use Rx\Scheduler\EventLoopScheduler;
use Rxnet\Observer\StdOutObserver;
require __DIR__ . "/../../vendor/autoload.php";
$loop = EventLoop::getLoop();
/*
 * If you have no statsd server, you can run the following command to listen for UDP traffic on port 8125 :
 * $> socat - udp4-listen:8125,reuseaddr,fork
 */
$statsd = new \Rxnet\Statsd\Statsd("localhost", 8125);
$req1 = $statsd->gauge("database.connections", 42);
$req2 = $statsd->increment("database.query.count");
$req3 = $statsd->histogram("database.query.time", 0.42);
Observable::mergeAll(Observable::fromArray([$req1, $req2, $req3]))->subscribe(new StdOutObserver(), new EventLoopScheduler($loop));
$loop->run();
コード例 #18
0
ファイル: distinct.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . '/../bootstrap.php';
$source = \Rx\Observable::fromArray([42, 24, 42, 24])->distinct();
$subscription = $source->subscribe($stdoutObserver);
コード例 #19
0
ファイル: groupBy.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . '/../bootstrap.php';
$observable = \Rx\Observable::fromArray([21, 42, 21, 42, 21, 42]);
$observable->groupBy(function ($elem) {
    if ($elem === 42) {
        return 0;
    }
    return 1;
}, null, function ($key) {
    return $key;
})->subscribeCallback(function ($groupedObserver) use($createStdoutObserver) {
    $groupedObserver->subscribe($createStdoutObserver($groupedObserver->getKey() . ": "));
});
コード例 #20
0
ファイル: Statsd.php プロジェクト: domraider/rxnet
 /**
  * Squirt the metrics over UDP
  *
  * @param array $data Incoming Data
  * @param float|1 $sampleRate the rate (0-1) for sampling.
  * @param array|string $tags Key Value array of Tag => Value, or single tag as string
  *
  * @return Observable
  **/
 public function send($data, $sampleRate = 1, array $tags = null)
 {
     // sampling
     $sampledData = array();
     if ($sampleRate < 1) {
         foreach ($data as $stat => $value) {
             if (mt_rand() / mt_getrandmax() <= $sampleRate) {
                 $sampledData[] = [$stat, "{$value}|@{$sampleRate}"];
             }
         }
     } else {
         foreach ($data as $stat => $value) {
             $sampledData[] = [$stat, $value];
         }
     }
     if (empty($sampledData)) {
         return Observable::emptyObservable();
     }
     $observableSequence = Observable::fromArray($sampledData)->map(function ($d) use($tags) {
         $stat = $d[0];
         $value = $d[1];
         if ($tags !== null && is_array($tags) && count($tags) > 0) {
             $value .= '|';
             foreach ($tags as $tag_key => $tag_val) {
                 if (is_array($tag_val)) {
                     $flattenTagVal = array();
                     array_walk_recursive($array, function ($a) use(&$return) {
                         $flattenTagVal[] = $a;
                     });
                     $tag_val = implode("\n", $flattenTagVal);
                 }
                 $value .= '#' . $tag_key . ':' . $tag_val . ',';
             }
             $value = substr($value, 0, -1);
         } elseif (isset($tags) && !empty($tags)) {
             $value .= '|#' . $tags;
         }
         return $this->reportMetric("{$stat}:{$value}");
     });
     return Observable::mergeAll($observableSequence);
 }
コード例 #21
0
 /**
  * @return ObservableInterface
  */
 public function broadcasts() : ObservableInterface
 {
     return Promise::toObservable($this->transport->request('broadcasts'))->flatMap(function ($response) {
         return Observable::fromArray($response['broadcasts']);
     })->map(function ($broadcast) {
         return $this->getTransport()->getHydrator()->hydrate('Broadcast', $broadcast);
     });
 }
コード例 #22
0
ファイル: multiple_gets.php プロジェクト: RxPHP/RxHttp
<?php

include __DIR__ . '/../../vendor/autoload.php';
$imageTypes = ["png", "jpeg", "webp"];
$images = \Rx\Observable::fromArray($imageTypes)->flatMap(function ($type) {
    return \Rx\React\Http::get("http://httpbin.org/image/{$type}")->map(function ($image) use($type) {
        return [$type => $image];
    });
});
$images->subscribeCallback(function ($data) {
    echo "Got Image: ", array_keys($data)[0], PHP_EOL;
}, function (\Exception $e) {
    echo $e->getMessage(), PHP_EOL;
}, function () {
    echo "completed", PHP_EOL;
});
コード例 #23
0
ファイル: throttle.php プロジェクト: ReactiveX/RxPHP
<?php

use React\EventLoop\Factory;
use Rx\Observable;
use Rx\Scheduler\EventLoopScheduler;
require_once __DIR__ . '/../bootstrap.php';
$loop = Factory::create();
$scheduler = new EventLoopScheduler($loop);
$times = [['value' => 0, 'time' => 100], ['value' => 1, 'time' => 600], ['value' => 2, 'time' => 400], ['value' => 3, 'time' => 900], ['value' => 4, 'time' => 200]];
// Delay each item by time and project value;
$source = Observable::fromArray($times)->flatMap(function ($item) {
    return Observable::just($item['value'])->delay($item['time']);
})->throttle(300);
$subscription = $source->subscribe($stdoutObserver, $scheduler);
$loop->run();
コード例 #24
0
ファイル: ch08.php プロジェクト: luijar/fp-php
println('Example 1');
\Rx\Observable::fromArray([1, 2, 3, 4])->subscribe(new \Rx\Observer\CallbackObserver(function ($x) {
    echo 'Next: ', $x, PHP_EOL;
}, function (Exception $ex) {
    echo 'Error: ', $ex->getMessage(), PHP_EOL;
}, function () {
    echo 'Completed', PHP_EOL;
}));
println('Example 2 Reduce Map Filter with Curry');
$isEven = function ($num) {
    return $num % 2 === 0;
};
$add = function ($x, $y) {
    return $x + $y;
};
$raiseTo = function ($power, $num) {
    return pow($num, $power);
};
$computeSquare = P::curry2($raiseTo)(2);
\Rx\Observable::fromArray([1, 2, 3, 4])->filter($isEven)->map($computeSquare)->reduce($add, 0)->subscribe($stdoutObserver());
//-> 20
println('Example 3 - Map');
\Rx\Observable::fromArray([1, 2, 3, 4])->map(function ($num) {
    return $num * $num;
})->subscribe(new \Rx\Observer\CallbackObserver(function ($x) {
    echo 'Next: ', $x, PHP_EOL;
}, function (Exception $ex) {
    echo 'Error: ', $ex->getMessage(), PHP_EOL;
}, function () {
    echo 'Completed', PHP_EOL;
}));
コード例 #25
0
 /**
  * @inheritDoc
  */
 public function __invoke(ObservableInterface $observable, ObserverInterface $observer, SchedulerInterface $scheduler = null)
 {
     return Observable::fromArray($this->startArray)->concat($observable)->subscribe($observer, $scheduler);
 }
コード例 #26
0
ファイル: max-with-comparer.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . "/../bootstrap.php";
/* With a comparer */
$comparer = function ($x, $y) {
    if ($x > $y) {
        return 1;
    } elseif ($x < $y) {
        return -1;
    }
    return 0;
};
$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])->max($comparer);
$subscription = $source->subscribe($createStdoutObserver());
コード例 #27
0
ファイル: reduce.php プロジェクト: ReactiveX/RxPHP
<?php

require_once __DIR__ . '/../bootstrap.php';
//Without a seed
$source = \Rx\Observable::fromArray(range(1, 3));
$subscription = $source->reduce(function ($acc, $x) {
    return $acc + $x;
})->subscribe($createStdoutObserver());
コード例 #28
0
ファイル: ReplaySubjectTest.php プロジェクト: voryx/Rx.PHP
 /**
  * @test
  */
 public function it_replays_with_no_scheduler()
 {
     $rs = new ReplaySubject();
     $o = Observable::fromArray(range(1, 5));
     $o->subscribe($rs);
     $result = [];
     $completed = false;
     $rs->subscribeCallback(function ($x) use(&$result) {
         $result[] = $x;
     }, function ($e) {
         $this->fail("Should not have failed");
     }, function () use(&$result, &$completed) {
         $completed = true;
         $this->assertEquals($result, range(1, 5));
     });
     $this->assertTrue($completed);
 }
コード例 #29
0
ファイル: toArray.php プロジェクト: voryx/Rx.PHP
<?php

use Rx\Observer\CallbackObserver;
require_once __DIR__ . '/../bootstrap.php';
$source = \Rx\Observable::fromArray([1, 2, 3, 4]);
$observer = $createStdoutObserver();
$subscription = $source->toArray()->subscribe(new CallbackObserver(function ($array) use($observer) {
    $observer->onNext(json_encode($array));
}, [$observer, "onError"], [$observer, "onCompleted"]));
//Next value: [1,2,3,4]
//Complete!
コード例 #30
0
ファイル: CountTest.php プロジェクト: voryx/Rx.PHP
 public function testCountAfterRange()
 {
     $xs = Observable::fromArray(range(1, 10));
     $results = $this->scheduler->startWithCreate(function () use($xs) {
         return $xs->count();
     });
     $this->assertMessages([onNext(211, 10), onCompleted(211)], $results->getMessages());
 }