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

PDF
Fundamentals of Apache Kafka
PPTX
MeetUp Monitoring with Prometheus and Grafana (September 2018)
PDF
Infrastructure & System Monitoring using Prometheus
PDF
Introduction to Azure Data Lake
PDF
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
PPTX
Stability Patterns for Microservices
PPTX
Kubernetes for Beginners: An Introductory Guide
PPTX
Introduction to Hadoop and Hadoop component
Fundamentals of Apache Kafka
MeetUp Monitoring with Prometheus and Grafana (September 2018)
Infrastructure & System Monitoring using Prometheus
Introduction to Azure Data Lake
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Stability Patterns for Microservices
Kubernetes for Beginners: An Introductory Guide
Introduction to Hadoop and Hadoop component

What's hot (20)

PPTX
Elastic Stack Introduction
PDF
Monitoring with prometheus
PDF
Building a Real-Time Analytics Application with Apache Pulsar and Apache Pinot
PPTX
Sharding Methods for MongoDB
PPTX
HBase and HDFS: Understanding FileSystem Usage in HBase
PDF
What's New in Apache Hive
PDF
An Introduction to Kubernetes
ODP
Monitoring With Prometheus
PPTX
Introduction to Docker - 2017
PPT
Monitoring using Prometheus and Grafana
PDF
Introduction to OpenStack
PDF
Ceph issue ν•΄κ²° 사둀
PDF
Apache Kafka Architecture & Fundamentals Explained
PPTX
Airflow presentation
PPTX
Apache Spark overview
PDF
Thanos: Global, durable Prometheus monitoring
PDF
Ansible
PDF
Airflow presentation
PPTX
Multi Cloud Architecture Approach
PPTX
Introduction to kubernetes
Elastic Stack Introduction
Monitoring with prometheus
Building a Real-Time Analytics Application with Apache Pulsar and Apache Pinot
Sharding Methods for MongoDB
HBase and HDFS: Understanding FileSystem Usage in HBase
What's New in Apache Hive
An Introduction to Kubernetes
Monitoring With Prometheus
Introduction to Docker - 2017
Monitoring using Prometheus and Grafana
Introduction to OpenStack
Ceph issue ν•΄κ²° 사둀
Apache Kafka Architecture & Fundamentals Explained
Airflow presentation
Apache Spark overview
Thanos: Global, durable Prometheus monitoring
Ansible
Airflow presentation
Multi Cloud Architecture Approach
Introduction to kubernetes
Ad

Viewers also liked (8)

PDF
Microservices - java ee vs spring boot and spring cloud
PPTX
Introduction to Kafka with Spring Integration
PDF
Introduction To Functional Reactive Programming Poznan
PPTX
Spring integration with the Java DSL
PDF
From object oriented to functional domain modeling
PDF
Microservice Architecture with CQRS and Event Sourcing
PDF
Integration Patterns and Anti-Patterns for Microservices Architectures
Β 
PPTX
Scaling wix with microservices architecture devoxx London 2015
Microservices - java ee vs spring boot and spring cloud
Introduction to Kafka with Spring Integration
Introduction To Functional Reactive Programming Poznan
Spring integration with the Java DSL
From object oriented to functional domain modeling
Microservice Architecture with CQRS and Event Sourcing
Integration Patterns and Anti-Patterns for Microservices Architectures
Β 
Scaling wix with microservices architecture devoxx London 2015
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
PDF
Reactive java - Reactive Programming + RxJava
PPTX
Reactive Programming in Java 8 with Rx-Java
PPTX
Intro to Functional Programming with RxJava
PPTX
Reactive programming with rx java
PPTX
RxJava 2 Reactive extensions for the JVM
PPTX
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
PDF
RxJava - introduction & design
PDF
Building Scalable Stateless Applications with RxJava
PDF
Streams, Streams Everywhere! An Introduction to Rx
PDF
The Mayans Lost Guide to RxJava on Android
PDF
Reactive Streams and RxJava2
PDF
Reactive x
PPTX
Intro to Reactive Thinking and RxJava 2
PDF
RxJava@Android
PPTX
Functional reactive programming
PDF
RxJava@DAUG
PDF
Reactive systems
PDF
How to Think in RxJava Before Reacting
PPTX
RxJava2 Slides
Β 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Reactive java - Reactive Programming + RxJava
Reactive Programming in Java 8 with Rx-Java
Intro to Functional Programming with RxJava
Reactive programming with rx java
RxJava 2 Reactive extensions for the JVM
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
RxJava - introduction & design
Building Scalable Stateless Applications with RxJava
Streams, Streams Everywhere! An Introduction to Rx
The Mayans Lost Guide to RxJava on Android
Reactive Streams and RxJava2
Reactive x
Intro to Reactive Thinking and RxJava 2
RxJava@Android
Functional reactive programming
RxJava@DAUG
Reactive systems
How to Think in RxJava Before Reacting
RxJava2 Slides
Β 

More from Mario Fusco (20)

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

Recently uploaded (20)

PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Introuction about ICD -10 and ICD-11 PPT.pptx
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
presentation_pfe-universite-molay-seltan.pptx
PDF
Triggering QUIC, presented by Geoff Huston at IETF 123
Β 
PPTX
Funds Management Learning Material for Beg
PPTX
Introuction about WHO-FIC in ICD-10.pptx
DOCX
Unit-3 cyber security network security of internet system
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PDF
Testing WebRTC applications at scale.pdf
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
PPTX
Internet___Basics___Styled_ presentation
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PPTX
SAP Ariba Sourcing PPT for learning material
PPT
tcp ip networks nd ip layering assotred slides
Module 1 - Cyber Law and Ethics 101.pptx
Introuction about ICD -10 and ICD-11 PPT.pptx
Decoding a Decade: 10 Years of Applied CTI Discipline
Tenda Login Guide: Access Your Router in 5 Easy Steps
presentation_pfe-universite-molay-seltan.pptx
Triggering QUIC, presented by Geoff Huston at IETF 123
Β 
Funds Management Learning Material for Beg
Introuction about WHO-FIC in ICD-10.pptx
Unit-3 cyber security network security of internet system
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PptxGenJS_Demo_Chart_20250317130215833.pptx
Testing WebRTC applications at scale.pdf
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
Internet___Basics___Styled_ presentation
introduction about ICD -10 & ICD-11 ppt.pptx
SAP Ariba Sourcing PPT for learning material
tcp ip networks nd ip layering assotred slides

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

  • 1. by Mario Fusco mario.fusco@gmail.com @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 mario.fusco@gmail.com twitter: @mariofusco Q A Thanks … Questions?