SlideShare a Scribd company logo
Reactive Programming
in PHP
Johney Park
2018.06.17
Reactive Programming
=
Observer Pattern
+ LINQ-style operators
( + Schedulers)
TL; DR
Pros:
Good for handling async events
Cons:
Difficult to understand
Too many things to learn
Some overhead
TL; DR
Definition
Reactive Programming is
programming with
asynchronous
data streams.
https://gist.github.com/
staltz/868e7e9bc2a7b8c1f754
(Where is reactive?)
What you heard when you
learn reactive programming
• Observer/Observable / Hot & Cold
• Signal / Flux / Stream / EventStream / EventSource / …
• Subject
• Scheduler
• Publish / Subscribe / Unsubscribe / Dispose / Behavior
• Producer / Consumer
• Map / Reduce / Throttle / …
Observer Pattern
Observer 1
Observable
watch & run
Observer 2
♨
(Event Source)
wrap
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
Observer Pattern
Observer 1
Observable 1
Observer 2
Observer 3
Subject 1
Subject 2
Subject = Observable + Observer
broadcast
♨
(Event Source)
♨
(Event Source)
direct call
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
RxPHP
• stream_select (PHP 4 >= 4.3.0, PHP 5, PHP 7)
• ReactPHP != RxPHP
• ReactPHP is event-driven, non-blocking I/O library
• EventLoop, Promise from ReactPHP
• https://github.com/ReactiveX/RxPHP
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
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
RxPHP
$subject = new RxSubjectSubject();
$subject ->subscribe(function($i) { echo $i . PHP_EOL;});
RxObservable ::interval(1000)
->take(5)
->flatMap(function ($i) {
return Observable ::of($i + 1);
})
->subscribe($subject);
$subject ->onNext(10);
$subject ->onNext(20);
$subject ->onNext(30);
// 10
// 20
// 30
// 1
// 2
// 3
// 4
// 5
Subject
• Subject = Observable +
Observer
• Actually Subject is extended
from Observable
• You don’t need to create custom
Observable for simple usage
RxPHP
More Samples
• https://github.com/ReactiveX/RxPHP/tree/master/demo
• https://github.com/PacktPublishing/PHP-Reactive-
Programming/
• https://www.packtpub.com/web-development/php-
reactive-programming
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?
The End

More Related Content

Similar to Reactive programming in PHP (20)

ODP
Implementing Comet using PHP
King Foo
 
PPTX
FailureEnrichers - Flink Meetup Bay Area.pptx
Panagiotis Garefalakis
 
PPTX
Reactive Extensions: classic Observer in .NET
EPAM
 
ODP
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
PDF
How I learned to time travel, or, data pipelining and scheduling with Airflow
PyData
 
PDF
Php 5.6 From the Inside Out
Ferenc Kovács
 
PDF
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
PPTX
Node.js primer
Quhan Arunasalam
 
PPTX
JDK8 Streams
Bansilal Haudakari
 
PDF
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
PPTX
Airflow 101
SaarBergerbest
 
PPT
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
PPTX
RxJava2 Slides
YarikS
 
PDF
php[world] 2016 - You Don’t Need Node.js - Async Programming in PHP
Adam Englander
 
PDF
Java 8 - Lambdas and much more
Alin Pandichi
 
PPTX
Introduction to Reactive programming
Dwi Randy Herdinanto
 
PPTX
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
PPTX
Asynchronous PHP - reactPHP et oui, ça existe!
Vanessa V.Chellen
 
PPTX
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PDF
How I learned to time travel, or, data pipelining and scheduling with Airflow
Laura Lorenz
 
Implementing Comet using PHP
King Foo
 
FailureEnrichers - Flink Meetup Bay Area.pptx
Panagiotis Garefalakis
 
Reactive Extensions: classic Observer in .NET
EPAM
 
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
PyData
 
Php 5.6 From the Inside Out
Ferenc Kovács
 
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
Node.js primer
Quhan Arunasalam
 
JDK8 Streams
Bansilal Haudakari
 
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
Airflow 101
SaarBergerbest
 
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
RxJava2 Slides
YarikS
 
php[world] 2016 - You Don’t Need Node.js - Async Programming in PHP
Adam Englander
 
Java 8 - Lambdas and much more
Alin Pandichi
 
Introduction to Reactive programming
Dwi Randy Herdinanto
 
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
Asynchronous PHP - reactPHP et oui, ça existe!
Vanessa V.Chellen
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
Laura Lorenz
 

Recently uploaded (20)

PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Thermal runway and thermal stability.pptx
godow93766
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Design Thinking basics for Engineers.pdf
CMR University
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Ad

Reactive programming in PHP

  • 2. Reactive Programming = Observer Pattern + LINQ-style operators ( + Schedulers) TL; DR
  • 3. Pros: Good for handling async events Cons: Difficult to understand Too many things to learn Some overhead TL; DR
  • 4. Definition Reactive Programming is programming with asynchronous data streams. https://gist.github.com/ staltz/868e7e9bc2a7b8c1f754 (Where is reactive?)
  • 5. What you heard when you learn reactive programming • Observer/Observable / Hot & Cold • Signal / Flux / Stream / EventStream / EventSource / … • Subject • Scheduler • Publish / Subscribe / Unsubscribe / Dispose / Behavior • Producer / Consumer • Map / Reduce / Throttle / …
  • 6. Observer Pattern Observer 1 Observable watch & run Observer 2 ♨ (Event Source) wrap
  • 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
  • 8. Observer Pattern Observer 1 Observable 1 Observer 2 Observer 3 Subject 1 Subject 2 Subject = Observable + Observer broadcast ♨ (Event Source) ♨ (Event Source) direct call
  • 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
  • 10. RxPHP • stream_select (PHP 4 >= 4.3.0, PHP 5, PHP 7) • ReactPHP != RxPHP • ReactPHP is event-driven, non-blocking I/O library • EventLoop, Promise from ReactPHP • https://github.com/ReactiveX/RxPHP
  • 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
  • 13. RxPHP $subject = new RxSubjectSubject(); $subject ->subscribe(function($i) { echo $i . PHP_EOL;}); RxObservable ::interval(1000) ->take(5) ->flatMap(function ($i) { return Observable ::of($i + 1); }) ->subscribe($subject); $subject ->onNext(10); $subject ->onNext(20); $subject ->onNext(30); // 10 // 20 // 30 // 1 // 2 // 3 // 4 // 5 Subject • Subject = Observable + Observer • Actually Subject is extended from Observable • You don’t need to create custom Observable for simple usage
  • 14. RxPHP More Samples • https://github.com/ReactiveX/RxPHP/tree/master/demo • https://github.com/PacktPublishing/PHP-Reactive- Programming/ • https://www.packtpub.com/web-development/php- reactive-programming
  • 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?