SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
SANG WON PARK
 

Tendances (20)

Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and Tomorrow
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafka
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafka
 
Apache Kafka - Martin Podval
Apache Kafka - Martin PodvalApache Kafka - Martin Podval
Apache Kafka - Martin Podval
 
Reliability Guarantees for Apache Kafka
Reliability Guarantees for Apache KafkaReliability Guarantees for Apache Kafka
Reliability Guarantees for Apache Kafka
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
 
kafka
kafkakafka
kafka
 
Introduction to Kafka connect
Introduction to Kafka connectIntroduction to Kafka connect
Introduction to Kafka connect
 
Apache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and DevelopersApache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and Developers
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
Reactive programming intro
Reactive programming introReactive programming intro
Reactive programming intro
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
Fundamentals of Apache Kafka
Fundamentals of Apache KafkaFundamentals of Apache Kafka
Fundamentals of Apache Kafka
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring Boot
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor Netty
 
Atomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas HunterAtomicity In Redis: Thomas Hunter
Atomicity In Redis: Thomas Hunter
 

En vedette

En vedette (8)

Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloud
 
Introduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationIntroduction to Kafka with Spring Integration
Introduction to Kafka with Spring Integration
 
Introduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming PoznanIntroduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming Poznan
 
Spring integration with the Java DSL
Spring integration with the Java DSLSpring integration with the Java DSL
Spring integration with the Java DSL
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Microservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingMicroservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event Sourcing
 
Integration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices ArchitecturesIntegration Patterns and Anti-Patterns for Microservices Architectures
Integration Patterns and Anti-Patterns for Microservices Architectures
 
Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015Scaling wix with microservices architecture devoxx London 2015
Scaling wix with microservices architecture devoxx London 2015
 

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

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
Sharma Podila
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
OdessaJS Conf
 
Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San Jose
Kostas Tzoumas
 

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

Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Apache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and Friends
 
Reactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka Streams
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
Flink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San JoseFlink Streaming Hadoop Summit San Jose
Flink Streaming Hadoop Summit San Jose
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Apache Flink Stream Processing
Apache Flink Stream ProcessingApache Flink Stream Processing
Apache Flink Stream Processing
 
Apache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault ToleranceApache Spark Streaming: Architecture and Fault Tolerance
Apache Spark Streaming: Architecture and Fault Tolerance
 

Plus de Mario Fusco

Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
Mario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
Mario Fusco
 

Plus de Mario Fusco (20)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
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...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Lazy java
Lazy javaLazy java
Lazy java
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 

Dernier

valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
sexy call girls service in goa
 

Dernier (20)

Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
Al Barsha Night Partner +0567686026 Call Girls Dubai
Al Barsha Night Partner +0567686026 Call Girls  DubaiAl Barsha Night Partner +0567686026 Call Girls  Dubai
Al Barsha Night Partner +0567686026 Call Girls Dubai
 
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 

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?