SlideShare a Scribd company logo
by Mario Fusco
mario.fusco@gmail.com
@mariofusco
Reactive Programming
for a demanding world:
building event-driven and
responsive applications with
RxJava
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 architectures!
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
Responsive
Resilient
Message Driven
Elastic
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 Composable
RxJava
Ratpack
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.»
— Heraclitus
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
How Netflix uses RxJava
From N network call ...
… to only 1
Pushing client logic to server
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
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);
Observable and Concurrency
An Observable is sequential → No concurrent emissions
Scheduling and combining Observables enables
concurrency while retaining sequential emission
Reactive Programming
requires a mental shift
from sync to async
from pull to push
from imperative to functional
Observing an Observable
Observer
Observable
time
subscribe
onNext*
onError | onCompleted
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
Enough speaking
Show me the code!
public class TempInfo {
public static final Random random = new Random();
public final String town;
public final int temp;
public TempInfo(String town, int temp) {
this.town = town;
this.temp = temp;
}
public static TempInfo fetch(String temp) {
return new TempInfo(temp, random.nextInt(70) - 20);
}
@Override
public String toString() {
return String.format(town + " : " + temp);
}
}
Fetching town's temperature
Creating Observables ...
public static Observable<TempInfo> getTemp(String town) {
return Observable.just(TempInfo.fetch(town));
}
public static Observable<TempInfo> getTemps(String... towns) {
return Observable.from(Stream.of(towns)
.map(town -> TempInfo.fetch(town))
.collect(toList()));
}
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(subscriber -> {
while (true) {
subscriber.onNext(TempInfo.fetch(town));
Thread.sleep(1000);
}
});
}
➢ … with just a single value
➢ … from an Iterable
➢ … from another Observable
Combining Observables
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(
subscriber -> Observable.interval(1, TimeUnit.SECONDS)
.subscribe(i -> subscriber
.onNext(TempInfo.fetch(town))));
}
public static Observable<TempInfo> getFeeds(String... towns) {
return Observable.merge(Arrays.stream(towns)
.map(town -> getFeed(town))
.collect(toList()));
}
➢ Subscribing one Observable to another
➢ Merging more Observables
Managing errors and completion
public static Observable<TempInfo> getFeed(String town) {
return Observable.create(subscriber ->
Observable.interval(1, TimeUnit.SECONDS)
.subscribe(i -> {
if (i > 5) subscriber.onCompleted();
try {
subscriber.onNext(TempInfo.fetch(town));
} catch (Exception e) {
subscriber.onError(e);
}
}));
}
Observable<TempInfo> feed = getFeeds("Milano", "Roma", "Napoli");
feed.subscribe(new Observer<TempInfo>() {
public void onCompleted() { System.out.println("Done!"); }
public void onError(Throwable t) {
System.out.println("Got problem: " + t);
}
public void onNext(TempInfo t) { System.out.println(t); }
});
Hot & Cold Observables
HOT
emits immediately whether its
Observer is ready or not
examples
mouse & keyboard events
system events
stock prices
time
COLD
emits at controlled rate when
requested by its Observers
examples
in-memory Iterable
database query
web service request
reading file
Dealing with a slow consumer
Push (reactive) when consumer keeps up with producer
Switch to Pull (interactive) when consumer is slow
observable.subscribe(new Subscriber<T>() {
@Override public void onStart() { request(1); }
@Override
public void onCompleted() { /* handle sequence-complete */ }
@Override
public void onError(Throwable e) { /* handle error */ }
@Override public void onNext(T n) {
// do something with the emitted item
request(1); // request another item
}
});
When you subscribe to an
Observable, you can request
reactive pull backpressure
Backpressure
Reactive pull
backpressure
isn’t magic
Backpressure doesn’t
make the problem of
an overproducing
Observable or an
underconsuming
Subscriber go away.
It just moves the
problem up the chain
of operators to a
point where it can be
handled better.
Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Q A
Thanks … Questions?

More Related Content

What's hot (20)

PDF
Apache Kafka Architecture & Fundamentals Explained
confluent
 
PDF
So You Want to Write a Connector?
confluent
 
PPTX
Kafka Tutorial - Introduction to Apache Kafka (Part 1)
Jean-Paul Azar
 
PPTX
Kafka replication apachecon_2013
Jun Rao
 
PPTX
A visual introduction to Apache Kafka
Paul Brebner
 
PPTX
HBase and HDFS: Understanding FileSystem Usage in HBase
enissoz
 
PDF
Handle Large Messages In Apache Kafka
Jiangjie Qin
 
PDF
Ansible
Kamil Lelonek
 
PDF
Jenkins-CI
Gong Haibing
 
PDF
[KubeCon EU 2020] containerd Deep Dive
Akihiro Suda
 
PDF
Kafka At Scale in the Cloud
confluent
 
PDF
Fundamentals of Apache Kafka
Chhavi Parasher
 
PDF
Kafka 101 and Developer Best Practices
confluent
 
PPTX
Jenkins CI
Viyaan Jhiingade
 
PPTX
APACHE KAFKA / Kafka Connect / Kafka Streams
Ketan Gote
 
PDF
NGINX Ingress Controller for Kubernetes
NGINX, Inc.
 
PDF
CI/CD with an Idempotent Kafka Producer & Consumer | Kafka Summit London 2022
HostedbyConfluent
 
PPTX
Kafka presentation
Mohammed Fazuluddin
 
PPTX
Introduction to ansible
Omid Vahdaty
 
KEY
ElasticSearch at berlinbuzzwords 2010
Elasticsearch
 
Apache Kafka Architecture & Fundamentals Explained
confluent
 
So You Want to Write a Connector?
confluent
 
Kafka Tutorial - Introduction to Apache Kafka (Part 1)
Jean-Paul Azar
 
Kafka replication apachecon_2013
Jun Rao
 
A visual introduction to Apache Kafka
Paul Brebner
 
HBase and HDFS: Understanding FileSystem Usage in HBase
enissoz
 
Handle Large Messages In Apache Kafka
Jiangjie Qin
 
Ansible
Kamil Lelonek
 
Jenkins-CI
Gong Haibing
 
[KubeCon EU 2020] containerd Deep Dive
Akihiro Suda
 
Kafka At Scale in the Cloud
confluent
 
Fundamentals of Apache Kafka
Chhavi Parasher
 
Kafka 101 and Developer Best Practices
confluent
 
Jenkins CI
Viyaan Jhiingade
 
APACHE KAFKA / Kafka Connect / Kafka Streams
Ketan Gote
 
NGINX Ingress Controller for Kubernetes
NGINX, Inc.
 
CI/CD with an Idempotent Kafka Producer & Consumer | Kafka Summit London 2022
HostedbyConfluent
 
Kafka presentation
Mohammed Fazuluddin
 
Introduction to ansible
Omid Vahdaty
 
ElasticSearch at berlinbuzzwords 2010
Elasticsearch
 

Viewers also liked (8)

PDF
Microservices - java ee vs spring boot and spring cloud
Ben Wilcock
 
PPTX
Introduction to Kafka with Spring Integration
Borislav Markov
 
PDF
Introduction To Functional Reactive Programming Poznan
Eliasz Sawicki
 
PPTX
Spring integration with the Java DSL
Ben Wilcock
 
PDF
From object oriented to functional domain modeling
Mario Fusco
 
PDF
Microservice Architecture with CQRS and Event Sourcing
Ben Wilcock
 
PDF
Integration Patterns and Anti-Patterns for Microservices Architectures
Apcera
 
PPTX
Scaling wix with microservices architecture devoxx London 2015
Aviran Mordo
 
Microservices - java ee vs spring boot and spring cloud
Ben Wilcock
 
Introduction to Kafka with Spring Integration
Borislav Markov
 
Introduction To Functional Reactive Programming Poznan
Eliasz Sawicki
 
Spring integration with the Java DSL
Ben Wilcock
 
From object oriented to functional domain modeling
Mario Fusco
 
Microservice Architecture with CQRS and Event Sourcing
Ben Wilcock
 
Integration Patterns and Anti-Patterns for Microservices Architectures
Apcera
 
Scaling wix with microservices architecture devoxx London 2015
Aviran Mordo
 
Ad

Similar to Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava (20)

PPTX
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Codemotion
 
PPTX
Reactive programming every day
Vadym Khondar
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
PDF
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
PPT
Reactive programming with examples
Peter Lawrey
 
PDF
Building Scalable Stateless Applications with RxJava
Rick Warren
 
PDF
Prezo tooracleteam (2)
Sharma Podila
 
PPTX
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
OdessaJS Conf
 
PDF
Rxjs kyivjs 2015
Alexander Mostovenko
 
PDF
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
PDF
Concurrecny inf sharp
Riccardo Terrell
 
PPTX
Apache Flink Overview at SF Spark and Friends
Stephan Ewen
 
PDF
Reactive Streams 1.0 and Akka Streams
Dean Wampler
 
PPTX
Stream processing - Apache flink
Renato Guimaraes
 
PPTX
Rxjs marble-testing
Christoffer Noring
 
PPTX
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
PPTX
Flink Streaming Hadoop Summit San Jose
Kostas Tzoumas
 
PPT
Server side JavaScript: going all the way
Oleg Podsechin
 
PDF
Apache Flink Stream Processing
Suneel Marthi
 
POTX
Apache Spark Streaming: Architecture and Fault Tolerance
Sachin Aggarwal
 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Codemotion
 
Reactive programming every day
Vadym Khondar
 
rx.js make async programming simpler
Alexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
Reactive programming with examples
Peter Lawrey
 
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Prezo tooracleteam (2)
Sharma Podila
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
OdessaJS Conf
 
Rxjs kyivjs 2015
Alexander Mostovenko
 
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Concurrecny inf sharp
Riccardo Terrell
 
Apache Flink Overview at SF Spark and Friends
Stephan Ewen
 
Reactive Streams 1.0 and Akka Streams
Dean Wampler
 
Stream processing - Apache flink
Renato Guimaraes
 
Rxjs marble-testing
Christoffer Noring
 
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
Flink Streaming Hadoop Summit San Jose
Kostas Tzoumas
 
Server side JavaScript: going all the way
Oleg Podsechin
 
Apache Flink Stream Processing
Suneel Marthi
 
Apache Spark Streaming: Architecture and Fault Tolerance
Sachin Aggarwal
 
Ad

More from Mario Fusco (20)

PDF
Kogito: cloud native business automation
Mario Fusco
 
PDF
Let's make a contract: the art of designing a Java API
Mario Fusco
 
PDF
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
PDF
OOP and FP
Mario Fusco
 
PDF
Lazy java
Mario Fusco
 
ODP
Drools 6 deep dive
Mario Fusco
 
PDF
OOP and FP - Become a Better Programmer
Mario Fusco
 
PDF
Comparing different concurrency models on the JVM
Mario Fusco
 
PDF
Java 8 Workshop
Mario Fusco
 
PDF
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
PDF
Monadic Java
Mario Fusco
 
PDF
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
PDF
FP in Java - Project Lambda and beyond
Mario Fusco
 
PDF
Why we cannot ignore Functional Programming
Mario Fusco
 
PPTX
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
PDF
Introducing Drools
Mario Fusco
 
PPTX
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
PDF
Hammurabi
Mario Fusco
 
PPT
Swiss army knife Spring
Mario Fusco
 
PDF
No more loops with lambdaj
Mario Fusco
 
Kogito: cloud native business automation
Mario Fusco
 
Let's make a contract: the art of designing a Java API
Mario Fusco
 
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
OOP and FP
Mario Fusco
 
Lazy java
Mario Fusco
 
Drools 6 deep dive
Mario Fusco
 
OOP and FP - Become a Better Programmer
Mario Fusco
 
Comparing different concurrency models on the JVM
Mario Fusco
 
Java 8 Workshop
Mario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
Monadic Java
Mario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
FP in Java - Project Lambda and beyond
Mario Fusco
 
Why we cannot ignore Functional Programming
Mario Fusco
 
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
Introducing Drools
Mario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Hammurabi
Mario Fusco
 
Swiss army knife Spring
Mario Fusco
 
No more loops with lambdaj
Mario Fusco
 

Recently uploaded (20)

PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPTX
原版一样(毕业证书)法国蒙彼利埃大学毕业证文凭复刻
Taqyea
 
PDF
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
PPTX
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
PPTX
Academic Debate: Creation vs Evolution.pptx
JOHNPATRICKMARTINEZ5
 
PDF
The Hidden Benefits of Outsourcing IT Hardware Procurement for Small Businesses
Carley Cramer
 
PDF
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
PPTX
原版一样(LHU毕业证书)英国利物浦希望大学毕业证办理方法
Taqyea
 
PDF
google promotion services in Delhi, India
Digital Web Future
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PPTX
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PDF
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
PDF
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PDF
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
原版一样(毕业证书)法国蒙彼利埃大学毕业证文凭复刻
Taqyea
 
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
Academic Debate: Creation vs Evolution.pptx
JOHNPATRICKMARTINEZ5
 
The Hidden Benefits of Outsourcing IT Hardware Procurement for Small Businesses
Carley Cramer
 
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
原版一样(LHU毕业证书)英国利物浦希望大学毕业证办理方法
Taqyea
 
google promotion services in Delhi, India
Digital Web Future
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 

Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava

  • 1. by Mario Fusco [email protected] @mariofusco Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava
  • 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 architectures!
  • 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 Responsive Resilient Message Driven Elastic
  • 5. 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 Composable RxJava Ratpack
  • 6. 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!
  • 7. 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
  • 8. See Events Streams Everywhere stock prices weather shop's orders flights/trains arrivals time mouse position
  • 10. 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.» — Heraclitus
  • 11. 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
  • 12. How Netflix uses RxJava From N network call ...
  • 13. … to only 1 Pushing client logic to server
  • 14. 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
  • 15. … and events' transformations
  • 16. RxJava operations as marble diagrams
  • 17. 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()
  • 18. 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);
  • 19. Observable and Concurrency An Observable is sequential → No concurrent emissions Scheduling and combining Observables enables concurrency while retaining sequential emission
  • 20. Reactive Programming requires a mental shift from sync to async from pull to push from imperative to functional
  • 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
  • 25. public class TempInfo { public static final Random random = new Random(); public final String town; public final int temp; public TempInfo(String town, int temp) { this.town = town; this.temp = temp; } public static TempInfo fetch(String temp) { return new TempInfo(temp, random.nextInt(70) - 20); } @Override public String toString() { return String.format(town + " : " + temp); } } Fetching town's temperature
  • 26. Creating Observables ... public static Observable<TempInfo> getTemp(String town) { return Observable.just(TempInfo.fetch(town)); } public static Observable<TempInfo> getTemps(String... towns) { return Observable.from(Stream.of(towns) .map(town -> TempInfo.fetch(town)) .collect(toList())); } public static Observable<TempInfo> getFeed(String town) { return Observable.create(subscriber -> { while (true) { subscriber.onNext(TempInfo.fetch(town)); Thread.sleep(1000); } }); } ➢ … with just a single value ➢ … from an Iterable ➢ … from another Observable
  • 27. Combining Observables public static Observable<TempInfo> getFeed(String town) { return Observable.create( subscriber -> Observable.interval(1, TimeUnit.SECONDS) .subscribe(i -> subscriber .onNext(TempInfo.fetch(town)))); } public static Observable<TempInfo> getFeeds(String... towns) { return Observable.merge(Arrays.stream(towns) .map(town -> getFeed(town)) .collect(toList())); } ➢ Subscribing one Observable to another ➢ Merging more Observables
  • 28. Managing errors and completion public static Observable<TempInfo> getFeed(String town) { return Observable.create(subscriber -> Observable.interval(1, TimeUnit.SECONDS) .subscribe(i -> { if (i > 5) subscriber.onCompleted(); try { subscriber.onNext(TempInfo.fetch(town)); } catch (Exception e) { subscriber.onError(e); } })); } Observable<TempInfo> feed = getFeeds("Milano", "Roma", "Napoli"); feed.subscribe(new Observer<TempInfo>() { public void onCompleted() { System.out.println("Done!"); } public void onError(Throwable t) { System.out.println("Got problem: " + t); } public void onNext(TempInfo t) { System.out.println(t); } });
  • 29. Hot & Cold Observables HOT emits immediately whether its Observer is ready or not examples mouse & keyboard events system events stock prices time COLD emits at controlled rate when requested by its Observers examples in-memory Iterable database query web service request reading file
  • 30. Dealing with a slow consumer Push (reactive) when consumer keeps up with producer Switch to Pull (interactive) when consumer is slow observable.subscribe(new Subscriber<T>() { @Override public void onStart() { request(1); } @Override public void onCompleted() { /* handle sequence-complete */ } @Override public void onError(Throwable e) { /* handle error */ } @Override public void onNext(T n) { // do something with the emitted item request(1); // request another item } }); When you subscribe to an Observable, you can request reactive pull backpressure
  • 31. Backpressure Reactive pull backpressure isn’t magic Backpressure doesn’t make the problem of an overproducing Observable or an underconsuming Subscriber go away. It just moves the problem up the chain of operators to a point where it can be handled better.
  • 32. Mario Fusco Red Hat – Senior Software Engineer [email protected] twitter: @mariofusco Q A Thanks … Questions?