7. Observer Pattern
Observer 1
Observable
subscribe
Lazy Evaluation
Subscription 1
async call with
stream operators
Observer 2 Subscription 2
Observers don’t observe
Observable does all the work
Producer / Consumer may be better naming
9. When to use RP?
• One or more event sources
• Require stream operators
• Not a perfect solution for all
async scenarios
• External API Call (MSA)
• UI Events (Click)
• Message Processing
• Abstraction over Async Process
11. RxPHP
$source = RxObservable ::fromArray([1, 2, 3, 4]);
$observer = new RxObserverCallbackObserver(
function ($x) {
echo 'Next: ', $x, PHP_EOL;
},
function (Exception $ex) {
echo 'Error: ', $ex ->getMessage(), PHP_EOL;
},
function () {
echo 'Completed', PHP_EOL;
});
$source ->subscribe($observer);
// Next: 1
// Next: 2
// Next: 3
// Next: 4
// Completed
Very simple sample code
• Cold Observable Sample, almost
useless
• Source = Observable
• Subscribe Observer to
Observable
• Observer is consist of three
functions
• next, error, completed
12. RxPHP
$loop = Factory ::create();
Scheduler ::setDefaultFactory(function () use ($loop) {
return new SchedulerEventLoopScheduler($loop);
});
register_shutdown_function(function () use ($loop) {
$loop ->run();
});
Observable ::interval(1000)
->take(5)
->flatMap(function ($i) {
return Observable ::of($i + 1);
})
->subscribe(function ($e) {
echo $e, PHP_EOL;
});
// 1
// 2
// 3
// 4
// 5
Event Loop
• We need to set EventLoop when using
stream operator
• interval, throttle, etc..
• If you don’t use stream operator, you
don’t need to set EventLoop
• RxJs don’t require explicit event loop,
because Javascript has setTimeout,
setInterval, requestAnimationFrame
• There are many scheduler types
• flatMap == mergeMap, but RxPHP don’t
provide mergeMap
15. RxPHP
Ben Lesh’s comment
RxJS could be so simple... just a handful of types and operators.
... but if we do that, then people shoot themselves in the foot with memory
leaks and their own poorly implemented `expand` operator or whatever… ...
so then we add 60+ operators and people are like "WHOA...." haha.. Now it's
too complicated.
It's tough everywhere. Haha
If I had a nickel for every poorly implemented custom RxJS operator I've
seen… ... I'd only have about 25 cents, because we've already built almost
every tool someone could want.
But who have we scared off in the process?