SlideShare a Scribd company logo
by Mario Fusco
mario.fusco@gmail.com
@mariofusco
Reactive Programming
in Java
Reactive
“readily responsive to a stimulus”
Merriam-Webster dictionary
Why reactive? What changed?
➢ Usage patterns: Users expect millisecond response times and 100% uptime
A few years ago largest applications had tens of servers and gigabytes of data
Seconds of response time and hours of offline maintenance were acceptable
Today
➢ Big Data: usually measured in Petabytes and
increasing with an extremely high frequency
➢ Heterogeneous environment: applications are deployed
on everything from mobile devices to cloud-based
clusters running thousands of multi-core processors
Today's demands are simply not met
by yesterday’s software
640K ought to be
enough for anybody
The Reactive Manifesto
The system responds in a timely manner
if at all possible. Responsiveness is the
cornerstone of usability The system stays
responsive in the
face of failure
The system stays
responsive under varying
workload. It can react to
changes in the input rate
by increasing or decreasing
the resources allocated to
service these inputs
The system rely on asynchronous message
passing to establish a boundary between
components that ensures loose coupling,
isolation and location transparency
Rethinking programming the
Reactive way
➢ Reactive programming is a programming paradigm about data-
flow
➢ Think in terms of discrete events and streams of them
➢ React to events and define behaviors combining them
➢ The system state changes over time based on the flow of events
➢ Keep your data/events immutable
Never
block!
Reactive programming is
programming with
asynchronous data streams
➢ A stream is a sequence
of ongoing events
ordered in time
➢ Events are processed
asynchronously, by
defining a function
that will be executed
when an event arrives
See Events Streams Everywhere
stock prices
weather
shop's
orders
flights/trains arrivals
time
mouse position
Reactive Programming Mantra
Streams are not collections
Streams are
➢ potentially unbounded in length
➢ focused on transformation of data
➢ time-dependent
➢ ephemeral
➢ traversable only once
«You cannot step twice into the same
stream. For as you are stepping in, other
waters are ever flowing on to you.»
The Reactive Streams Initiative
Reactive Streams is an initiative to provide a standard for
asynchronous stream processing with non-blocking back pressure on
the JVM
Problem
Handling streams of (live) data
in an asynchronous and
possibly non-blocking way
Scope
Finding a minimal API
describing the operations
available on Reactive Streams
Implementors
Akka Streams
Reactor
RxJava
Ratpack
Vert.x
The Java 9 Flow API
@FunctionalInterface
public interface Publisher<T> {
void subscribe(Subscriber<? super T> s);
}
public interface Subscriber<T> {
void onSubscribe(Subscription s);
void onNext(T t);
void onError(Throwable t);
void onComplete();
}
public interface Subscription {
void request(long n);
void cancel();
}
public interface Processor<T, R> extends Subscriber<T>,
Publisher<R> {
}
Reactive Application Lifecycle
Publisher Subscriber
subscribe(Subscriber)
Main
onSubscribe(Subscription)
Subscription
onNext(data)
onNext(data)
request(int)
onNext(data)
onComplete/onError
onSubscribe onNext* (onError | onComplete)?
backpressure
request(int)
Enough speaking
Show me the code!
RxJava
Reactive Extension for async
programming➢ A library for composing asynchronous and event-based
programs using observable sequences for the Java VM
➢ Supports Java 6 or higher and JVM-based languages such as
Groovy, Clojure, JRuby, Kotlin and Scala
➢ Includes a DSL providing extensive operations for streams
transformation, filtering and recombination
➢ Implements pure “push” model
➢ Decouple events production from consumption
➢ Allows blocking only for back pressure
➢ First class support for error handling,
➢ scheduling & flow control
➢ Used by Netflix to make the entire service
➢ layer asynchronous
http://reactivex.io
http://github.com/ReactiveX/RxJava
Observable
The Observable interface defines how to access
asynchronous sequences of multiple items
single value multiple values
synchronous T getData() Iterable<T> getData()
asynchronous Future<T> getData() Observable<T> getData()
An Observable is the asynchronous/push “dual” to the synchronous/pull Iterable
Iterable (pull) Obesrvable (push)
retrieve data T next() onNext(T)
signal error throws Exception onError(Exception)
completion !hasNext() onCompleted()
Observable as async Stream
// Stream<Stock> containing 100 Stocks
getDataFromLocalMemory()
.skip(10)
.filter(s -> s.getValue > 100)
.map(s -> s.getName() + “: ” + s.getValue())
.forEach(System.out::println);
// Observable<Stock> emitting 100 Stocks
getDataFromNetwork()
.skip(10)
.filter(s -> s.getValue > 100)
.map(s -> s.getName() + “: ” + s.getValue())
.forEach(System.out::println);
Marble diagrams:
Representing events' streams ...
A stream is a sequence of ongoing events ordered in time.
It can emit three different things:
1. a value (of some type) 2. an error 3. "completed" signal
… and events' transformations
RxJava operations as marble
diagrams
What do you want? More code!
When do you it? Now!
Observable and Concurrency
An Observable is sequential → No concurrent emissions
Scheduling and combining Observables enables
concurrency while retaining sequential emission
How is the Observable implemented?
➢ Maybe it executes its logic on subscriber thread?
➢ Maybe it delegates part of the work to other threads?
➢ Does it use NIO?
➢ Maybe it is an actor?
➢ Does it return cached data?
Observer
does not
care!
public interface Observer<T> {
void onCompleted();
void onError(Throwable var1);
void onNext(T var1);
}
Non-Opinionated Concurrency
Observable Observer
Calling
Thread
Callback
Thread
onNext
Work synchronously on calling thread
Observable Observer
Calling
Thread
Callback
Thread
onNext
Work asynchronously on separate thread
Thread
pool
Observable Observer
Calling
Thread
Callback
Threads
onNext
Work asynchronously on multiple threads
Thread
pool
Could be an actor or an event loop
Reactive Programming
requires a mental shift
from sync to
async
from pull to push
from imperative to functional
Mario Fusco
Red Hat – Senior Software
Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Q A
Thanks … Questions?

More Related Content

PPTX
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Codemotion
 
PDF
Reactive stream processing using Akka streams
Johan Andrén
 
PDF
Streaming all the things with akka streams
Johan Andrén
 
PDF
Buiilding reactive distributed systems with Akka
Johan Andrén
 
PDF
Reactive streams processing using Akka Streams
Johan Andrén
 
PDF
Next generation actors with Akka
Johan Andrén
 
PDF
Next generation message driven systems with Akka
Johan Andrén
 
PDF
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Codemotion
 
Reactive stream processing using Akka streams
Johan Andrén
 
Streaming all the things with akka streams
Johan Andrén
 
Buiilding reactive distributed systems with Akka
Johan Andrén
 
Reactive streams processing using Akka Streams
Johan Andrén
 
Next generation actors with Akka
Johan Andrén
 
Next generation message driven systems with Akka
Johan Andrén
 
Building Scalable Stateless Applications with RxJava
Rick Warren
 

What's hot (20)

PDF
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
PDF
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Konrad Malawski
 
PDF
Networks and types - the future of Akka
Johan Andrén
 
PDF
Reactive Applications in Java
Alexander Mrynskyi
 
PDF
A dive into akka streams: from the basics to a real-world scenario
Gioia Ballin
 
PDF
Akka Streams - From Zero to Kafka
Mark Harrison
 
PDF
Scala usergroup stockholm - reactive integrations with akka streams
Johan Andrén
 
PDF
Next generation message driven systems with Akka
Johan Andrén
 
PDF
Reactive Streams: Handling Data-Flow the Reactive Way
Roland Kuhn
 
PPTX
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
PDF
Building reactive distributed systems with Akka
Johan Andrén
 
PDF
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
Konrad Malawski
 
PDF
Resilient Applications with Akka Persistence - Scaladays 2014
Björn Antonsson
 
PDF
End to End Akka Streams / Reactive Streams - from Business to Socket
Konrad Malawski
 
PDF
The Need for Async @ ScalaWorld
Konrad Malawski
 
PDF
Reactive integrations with Akka Streams
Konrad Malawski
 
PPTX
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
PDF
The Cloud-natives are RESTless @ JavaOne
Konrad Malawski
 
PPTX
Topic Modeling via Tensor Factorization Use Case for Apache REEF Framework
DataWorks Summit
 
PPTX
Topic Modeling via Tensor Factorization - Use Case for Apache REEF
Sergiy Matusevych
 
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Konrad Malawski
 
Networks and types - the future of Akka
Johan Andrén
 
Reactive Applications in Java
Alexander Mrynskyi
 
A dive into akka streams: from the basics to a real-world scenario
Gioia Ballin
 
Akka Streams - From Zero to Kafka
Mark Harrison
 
Scala usergroup stockholm - reactive integrations with akka streams
Johan Andrén
 
Next generation message driven systems with Akka
Johan Andrén
 
Reactive Streams: Handling Data-Flow the Reactive Way
Roland Kuhn
 
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Building reactive distributed systems with Akka
Johan Andrén
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
Konrad Malawski
 
Resilient Applications with Akka Persistence - Scaladays 2014
Björn Antonsson
 
End to End Akka Streams / Reactive Streams - from Business to Socket
Konrad Malawski
 
The Need for Async @ ScalaWorld
Konrad Malawski
 
Reactive integrations with Akka Streams
Konrad Malawski
 
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
The Cloud-natives are RESTless @ JavaOne
Konrad Malawski
 
Topic Modeling via Tensor Factorization Use Case for Apache REEF Framework
DataWorks Summit
 
Topic Modeling via Tensor Factorization - Use Case for Apache REEF
Sergiy Matusevych
 
Ad

Similar to Mario Fusco - Reactive programming in Java - Codemotion Milan 2017 (20)

PDF
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
PDF
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
PPT
Reactive programming with examples
Peter Lawrey
 
PDF
Prezo tooracleteam (2)
Sharma Podila
 
PPTX
Apache Flink Overview at SF Spark and Friends
Stephan Ewen
 
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
PDF
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Konrad Malawski
 
PDF
Reactive Streams 1.0 and Akka Streams
Dean Wampler
 
PDF
DZone_RC_RxJS
Luis Atencio
 
PDF
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
PPTX
Flink Streaming Hadoop Summit San Jose
Kostas Tzoumas
 
PDF
Lightning Fast Monitoring against Lightning Fast Outages
Maxime Petazzoni
 
PPTX
Telegraph Cq English
Alberto Minetti
 
POTX
Apache Spark Streaming: Architecture and Fault Tolerance
Sachin Aggarwal
 
PDF
Multi-service reactive streams using Spring, Reactor, RSocket
Stéphane Maldini
 
PPT
Server side JavaScript: going all the way
Oleg Podsechin
 
PDF
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
Sean Zhong
 
PPTX
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
PDF
Cassandra 2.1 boot camp, Overview
Joshua McKenzie
 
PDF
Linux capacity planning
Francisco Gonçalves
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Reactive programming with examples
Peter Lawrey
 
Prezo tooracleteam (2)
Sharma Podila
 
Apache Flink Overview at SF Spark and Friends
Stephan Ewen
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Konrad Malawski
 
Reactive Streams 1.0 and Akka Streams
Dean Wampler
 
DZone_RC_RxJS
Luis Atencio
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
Flink Streaming Hadoop Summit San Jose
Kostas Tzoumas
 
Lightning Fast Monitoring against Lightning Fast Outages
Maxime Petazzoni
 
Telegraph Cq English
Alberto Minetti
 
Apache Spark Streaming: Architecture and Fault Tolerance
Sachin Aggarwal
 
Multi-service reactive streams using Spring, Reactor, RSocket
Stéphane Maldini
 
Server side JavaScript: going all the way
Oleg Podsechin
 
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
Sean Zhong
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
Cassandra 2.1 boot camp, Overview
Joshua McKenzie
 
Linux capacity planning
Francisco Gonçalves
 
Ad

More from Codemotion (20)

PDF
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
PDF
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
PPTX
Pastore - Commodore 65 - La storia
Codemotion
 
PPTX
Pennisi - Essere Richard Altwasser
Codemotion
 
PPTX
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
PPTX
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
PDF
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
PDF
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
PDF
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
PDF
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
PDF
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
PDF
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
PPTX
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
PDF
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
PDF
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
PDF
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
PDF
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Codemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 

Recently uploaded (20)

PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PPTX
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Software Development Methodologies in 2025
KodekX
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
Software Development Company | KodekX
KodekX
 
Doc9.....................................
SofiaCollazos
 
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Software Development Methodologies in 2025
KodekX
 

Mario Fusco - Reactive programming in Java - Codemotion Milan 2017

  • 2. Reactive “readily responsive to a stimulus” Merriam-Webster dictionary
  • 3. Why reactive? What changed? ➢ Usage patterns: Users expect millisecond response times and 100% uptime A few years ago largest applications had tens of servers and gigabytes of data Seconds of response time and hours of offline maintenance were acceptable Today ➢ Big Data: usually measured in Petabytes and increasing with an extremely high frequency ➢ Heterogeneous environment: applications are deployed on everything from mobile devices to cloud-based clusters running thousands of multi-core processors Today's demands are simply not met by yesterday’s software 640K ought to be enough for anybody
  • 4. The Reactive Manifesto The system responds in a timely manner if at all possible. Responsiveness is the cornerstone of usability The system stays responsive in the face of failure The system stays responsive under varying workload. It can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs The system rely on asynchronous message passing to establish a boundary between components that ensures loose coupling, isolation and location transparency
  • 5. Rethinking programming the Reactive way ➢ Reactive programming is a programming paradigm about data- flow ➢ Think in terms of discrete events and streams of them ➢ React to events and define behaviors combining them ➢ The system state changes over time based on the flow of events ➢ Keep your data/events immutable Never block!
  • 6. Reactive programming is programming with asynchronous data streams ➢ A stream is a sequence of ongoing events ordered in time ➢ Events are processed asynchronously, by defining a function that will be executed when an event arrives
  • 7. See Events Streams Everywhere stock prices weather shop's orders flights/trains arrivals time mouse position
  • 9. Streams are not collections Streams are ➢ potentially unbounded in length ➢ focused on transformation of data ➢ time-dependent ➢ ephemeral ➢ traversable only once «You cannot step twice into the same stream. For as you are stepping in, other waters are ever flowing on to you.»
  • 10. The Reactive Streams Initiative Reactive Streams is an initiative to provide a standard for asynchronous stream processing with non-blocking back pressure on the JVM Problem Handling streams of (live) data in an asynchronous and possibly non-blocking way Scope Finding a minimal API describing the operations available on Reactive Streams Implementors Akka Streams Reactor RxJava Ratpack Vert.x
  • 11. The Java 9 Flow API @FunctionalInterface public interface Publisher<T> { void subscribe(Subscriber<? super T> s); } public interface Subscriber<T> { void onSubscribe(Subscription s); void onNext(T t); void onError(Throwable t); void onComplete(); } public interface Subscription { void request(long n); void cancel(); } public interface Processor<T, R> extends Subscriber<T>, Publisher<R> { }
  • 12. Reactive Application Lifecycle Publisher Subscriber subscribe(Subscriber) Main onSubscribe(Subscription) Subscription onNext(data) onNext(data) request(int) onNext(data) onComplete/onError onSubscribe onNext* (onError | onComplete)? backpressure request(int)
  • 14. RxJava Reactive Extension for async programming➢ A library for composing asynchronous and event-based programs using observable sequences for the Java VM ➢ Supports Java 6 or higher and JVM-based languages such as Groovy, Clojure, JRuby, Kotlin and Scala ➢ Includes a DSL providing extensive operations for streams transformation, filtering and recombination ➢ Implements pure “push” model ➢ Decouple events production from consumption ➢ Allows blocking only for back pressure ➢ First class support for error handling, ➢ scheduling & flow control ➢ Used by Netflix to make the entire service ➢ layer asynchronous http://reactivex.io http://github.com/ReactiveX/RxJava
  • 15. Observable The Observable interface defines how to access asynchronous sequences of multiple items single value multiple values synchronous T getData() Iterable<T> getData() asynchronous Future<T> getData() Observable<T> getData() An Observable is the asynchronous/push “dual” to the synchronous/pull Iterable Iterable (pull) Obesrvable (push) retrieve data T next() onNext(T) signal error throws Exception onError(Exception) completion !hasNext() onCompleted()
  • 16. Observable as async Stream // Stream<Stock> containing 100 Stocks getDataFromLocalMemory() .skip(10) .filter(s -> s.getValue > 100) .map(s -> s.getName() + “: ” + s.getValue()) .forEach(System.out::println); // Observable<Stock> emitting 100 Stocks getDataFromNetwork() .skip(10) .filter(s -> s.getValue > 100) .map(s -> s.getName() + “: ” + s.getValue()) .forEach(System.out::println);
  • 17. Marble diagrams: Representing events' streams ... A stream is a sequence of ongoing events ordered in time. It can emit three different things: 1. a value (of some type) 2. an error 3. "completed" signal
  • 18. … and events' transformations
  • 19. RxJava operations as marble diagrams
  • 20. What do you want? More code! When do you it? Now!
  • 21. Observable and Concurrency An Observable is sequential → No concurrent emissions Scheduling and combining Observables enables concurrency while retaining sequential emission
  • 22. How is the Observable implemented? ➢ Maybe it executes its logic on subscriber thread? ➢ Maybe it delegates part of the work to other threads? ➢ Does it use NIO? ➢ Maybe it is an actor? ➢ Does it return cached data? Observer does not care! public interface Observer<T> { void onCompleted(); void onError(Throwable var1); void onNext(T var1); }
  • 23. Non-Opinionated Concurrency Observable Observer Calling Thread Callback Thread onNext Work synchronously on calling thread Observable Observer Calling Thread Callback Thread onNext Work asynchronously on separate thread Thread pool Observable Observer Calling Thread Callback Threads onNext Work asynchronously on multiple threads Thread pool Could be an actor or an event loop
  • 24. Reactive Programming requires a mental shift from sync to async from pull to push from imperative to functional
  • 25. Mario Fusco Red Hat – Senior Software Engineer [email protected] twitter: @mariofusco Q A Thanks … Questions?