SlideShare a Scribd company logo
Reactive Streams and
RxJava2
Yakov Fain, Farata Systems



yfain
About myself
• Solutions Architect at Farata Systems
• Java Champion
• Latest book:

“Angular 2 Development with TypeScript”

“If I had asked people what they wanted,
they would have said faster horses”



Henry Ford

Synchronous vs asynchronous
• Synchronous programming is straightforward
• Asynchronous programming dramatically increases complexity
Challenges in async programming
• Handling failed async requests
• Chaining async calls
• The user already closed the view
• Switching threads to update UI
and more challenges
• Avoiding writing blocking code in a multi-threaded app
• Several consumers
• Composable functions
• Killing a pending Http request
Backpressure
Subscriber

Sammy
A publisher generates more data than a subscriber can process
Publisher
Examples of backpressure
• The stock price changes 100 times a second
• Accelerometer produces 50 signals a second
• Iteration through a JDBC result set (rxjava-jdbc; rxjava2-jdbc)
• A user drags the mouse to draw a curve. Can’t apply back pressure.
Reactive Apps
• The data is processed as streams
• Message-driven: notifications
• Resilient: stay alive in case of failures
• Data flows through your app’s algorithms
• Hide complexity of multi-threading
Reactive Streams
• A spec for async stream processing with non-blocking backpressure



http://www.reactive-streams.org

• Reactive Streams interfaces for JVM 



https://github.com/reactive-streams/reactive-streams-jvm
• Reactive Streams-based products: 



RxJava2, Java 9 Flow APIs, Reactor 3, Akka Stream, MongoDB, Vert.x …
Reactive Streams: Java interfaces
Reactive Streams: Java interfaces
Reactive Streams: Java interfaces
backpressure

support
Reactive Streams: Java interfaces
backpressure

support
Main RxJava2 players
• Observable or Flowable - producers of data
• Observer or Subscriber - consumers of data
• Subject or Processor - implements both producer and consumer
• Operator - en-route data transformation
• Scheduler - multi-threading support
Main Publishers and Subscribers in RxJava2
Observable

no backpressure support


public interface Observer<T> {

void onSubscribe(Disposable var1);



void onNext(T var1);



void onError(Throwable var1);



void onComplete();

}
Publisher Subscriber
Not from 

Reactive Streams
Observable

no backpressure support
Flowable

with backpressure support
public interface Observer<T> {

void onSubscribe(Disposable var1);



void onNext(T var1);



void onError(Throwable var1);



void onComplete();

}
public interface Subscriber<T> {

void onSubscribe(Subscription var1);



void onNext(T var1);



void onError(Throwable var1);



void onComplete();

}
Not from 

Reactive Streams
From 

Reactive Streams
Main publishers and subscribers in RxJava2
Publisher Subscriber
Creating an Observable
• Observable.create()
• Observable.fromArray()
• Observable.fromIterable()
• Observable.fromCallable()
• Observable.fromFuture()
• Observable.range()
• Observable.just()
Observable.create(subscriber -> {
int totalBeers = beerStock.size();
for (int i = 0; i < totalBeers; i++) {

// synchronous push
subscriber.onNext(beerStock.get(i));
}
subscriber.onComplete();
});
Observable<Beer> observableBeer = Observable.create(/* data source */);
observableBeer

.skip(1)

.take(3)

.filter(beer -> "USA".equals(beer.country))

.map(beer -> beer.name + ": $" + beer.price)

.subscribe(

beer -> System.out.println(beer),



err -> System.out.println(err),



() -> System.out.println("Streaming is complete”),



disposable -> System.out.println( 

"Someone just subscribed to the beer stream!!!”)

);

);
Observable push
O
b
s
e
r
v
e
r
Subscription
Creating an Observer and subscribing
Observable<Beer> beerData = BeerServer.getData(); // returns an Observable



Observer beerObserver = new Observer<Beer>() {



public void onSubscribe(Disposable d) {

System.out.println( " !!! Someone just subscribed to the bear stream!!! ");



// If the subscriber is less than 21 year old, cancel subscription

// d.dispose();

}



public void onNext(Beer beer) {

System.out.println(beer);

}



public void onError(Throwable throwable) {

System.err.println("In Observer.onError(): " + throwable.getMessage());

}



public void onComplete() {

System.out.println("*** The stream is over ***");

}

};



beerData

.subscribe(beerObserver); // Streaming starts here
Subscription subscription = Observable.create(new Observable.OnSubscribe<Response>() {

OkHttpClient client = new OkHttpClient();



@Override
public void call(Subscriber<? super Response> subscriber) { // invoked on subscription
try {
Response response = client.newCall( // prepare the call for future execution
new Request.Builder().url(“http://localhost:8080/beers“)
.build())
.execute(); // use enqueue() for async requests


subscriber.onNext(response);



subscriber.onComplete();


if (!response.isSuccessful()) {
subscriber.onError(new Exception(“Can’t get beers”));
}
} catch (IOException e) {
subscriber.onError(e);
}
}
})

.subscribe(...); // pass Observer; use observeOn/SubscribeOn to switch threads
Pushing HTTP responses
https://square.github.io/okhttp
Controlling the flow with request()
request(1); request(1);
Handling backpressure
Publisher Subscriber
request(1)
request(3)
…
request() is non-blocking
onNext(value1)
onNext(value2)
onNext(value3)
onNext(value4)
BackpressureStrategy.BUFFER
BackpressureStrategy.BUFFER
BackpressureStrategy.DROP
BackpressureStrategy.Drop
BackpressureStrategy.LATEST
BackpressureStrategy.Latest
Creating a Flowable
• Flowable.create()
• Flowable.fromArray()
• Flowable.fromIterable()
• Flowable.fromCallable()
• Flowable.empty()
• Flowable.range()
• Flowable.just()
Flowable.create() and
Observable.toFlowable()
myObservable

.toFlowable(BackpressureStrategy.BUFFER);
Flowable<Beer> myFlowable

.create(beerEmitter ->{…},

BackpressureStrategy.BUFFER);
Create
Convert from Observable
Requesting data from Flowable
public class FlowableRange {



static DisposableSubscriber<Integer> subscriber;



public static void main(String[] args) {



subscriber = new DisposableSubscriber<Integer>() {



public void onStart() {

request(5);



while (true){ // Emulate 1-sec processing

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

request(1);

}

}



public void onNext(Integer t) {

System.out.println("processing "+ t);

if (t==8) { // just to demo unsubscribing

subscriber.dispose();

}

}



public void onError(Throwable thr) {

System.err.println("In onError(): " + thr.getMessage());


}



public void onComplete() {

System.out.println("Done");

}

};



Flowable.range(1, 10)

.subscribe(subscriber);

}

}
Demo 

1. FlowableRange

2. BeerClientFlowable
Code samples: https://github.com/yfain/rxjava2
An Operator
Observable Observable
A transforming

function
observableBeer

.filter(b -> "USA".equals(b.country))
Docs: http://reactivex.io/documentation/operators
QUIZ: What value(s) this observable emits?
Observable

.just(5, 9, 10) // emits 5, 9, 10



.filter(i -> i % 3 > 0)



.map(n -> "$" + n * 10)



.filter(s -> s.length() < 4);
Observable

.just(5, 9, 10) // emits 5, 9, 10



.filter(i -> i % 3 > 0)



.map(n -> "$" + n * 10)



.filter(s -> s.length() < 4)


.subscribe(System.out::println);
Composing observables
merge: combining observables
concat: combining observables in order
zip: combining observables of different types
flatMap
switchMap
Types of Observables
Hot Cold
Push
Produce a steam even

if no-one cares
r
Produce a stream when 

someone asks for it
✔
Hot Observables
• Mouse events
• Publishing stock prices
• An accelerometer in a smartphone
Making observables hot
Turning a cold observable into hot
ConnectableObservable<Long> numbers = (ConnectableObservable<Long>) Observable

.interval(1, TimeUnit.SECONDS) // generate seq numbers every second

.publish(); // make it hot



numbers.connect(); // creates an internal subscriber to start producing data

numbers.subscribe(n ->System.out.println("First subscriber: "+ n ));



Thread.sleep(3000);



numbers.subscribe(n ->System.out.println(" Second subscriber: "+ n ));

Demo 

HotObservable
Schedulers
Concurrency with Schedulers
• subscribeOn(strategy) - run Observable in a separate thread: 

Operations with side effects like files I/O;

Don’t hold off the UI thread

• observeOn(strategy) - run Observer in a separate thread,

Update Swing UI on the Event Dispatch Thread

Update Android UI on the Main thread
Multi-threading strategies
• Schedulers.computation() - for computations: # of threads <= # of cores
• Schedulers.io() - for long running communications; backed by a thread pool
• Schedulers.newThread() - new thread for each unit of work
• Schedulers.from(Executor) - a wrapper for Java Executor
• Schedulers.trampoline() - queues the work on the current thread
• AndroidSchedulers.mainThread() - handle data on the main thread (RxAndroid)
Switching threads
Operator1() Operator2() ObserveOn()
Observable
Subscriber
Thread 1
Thread 2
subscribeOn()
observeOn()
Multi-threaded processing with flatMap()
Operator1() Operator2() flatMap()
Observable
Subscriber
Thread 1
Observable/Thr2
Observable/Thr3
Observable/ThrN
Spawn a separate thread for each observable
…
Turning a value into

an observable
Observable.range(1, 1000)
.flatMap(n->Observable.just(n)

.subscribeOn(Schedulers.computation()))

.map(n->n*2)

.observeOn(AndroidSchedulers.mainThread())

.subscribe(myView.update());
Subscribing to each
observable on the
computation thread
Switching to the
main thread
Updating the UI
Demo 

schedulers/SubscribeOnObserveOn



ParallelStreams
Parallel operations with ParallelFlowabe
• Parallel execution of some operators

• The source sequence is dispatched into N parallel “rails”
• runOn() —-> sequential() is more efficient fork/join than flatMap()

• Each rail can spawn multiple async threads with Schedulers
Parallel Execution
int numberOfRails = 4; // can query #processors with parallelism()



ParallelFlowable

.from(Flowable.range(1, 10), numberOfRails)

.runOn(Schedulers.computation())

.map(i -> i * i)

.filter(i -> i % 3 == 0)

.sequential()

.subscribe(System.out::println);
Tasks run simultaneously on different CPUs or computers.
ParallelFlowableRange.java
Summary
• Observable: no backpressure support
• Flowable: backpressure support
• Operators can be chained
• flatmap() used for handling observable of observables
• Schedulers support multi-threading
• subscribeOn()/observeOn() - switching between threads
• ParallelFlowable - initiate parallel processing
Links
• Slides: http://bit.ly/2q3Ovt4
• Code samples: 

https://github.com/yfain/rxjava2
• Our company: faratasystems.com
• Blog: yakovfain.com
• Twitter: @yfain


More Related Content

PDF
Reactive programming in Angular 2
Yakov Fain
 
PDF
Reactive Thinking in Java with RxJava2
Yakov Fain
 
PDF
Web sockets in Angular
Yakov Fain
 
PDF
Reactive Thinking in Java
Yakov Fain
 
PDF
Intro to JavaScript
Yakov Fain
 
PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Angular2 Development for Java developers
Yakov Fain
 
PPTX
Angular 2 Migration - JHipster Meetup 6
William Marques
 
Reactive programming in Angular 2
Yakov Fain
 
Reactive Thinking in Java with RxJava2
Yakov Fain
 
Web sockets in Angular
Yakov Fain
 
Reactive Thinking in Java
Yakov Fain
 
Intro to JavaScript
Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Angular2 Development for Java developers
Yakov Fain
 
Angular 2 Migration - JHipster Meetup 6
William Marques
 

What's hot (20)

PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Intro to Retrofit 2 and RxJava2
Fabio Collini
 
PDF
Java Intro: Unit1. Hello World
Yakov Fain
 
PDF
Overview of the AngularJS framework
Yakov Fain
 
PDF
Test Driven Development with JavaFX
Hendrik Ebbers
 
PDF
Serverless functions with Micronaut
Alvaro Sanchez-Mariscal
 
PDF
AngularJS Unit Test
Chiew Carol
 
PDF
React state management with Redux and MobX
Darko Kukovec
 
PDF
The Many Ways to Test Your React App
All Things Open
 
PPTX
Single Page Applications with AngularJS 2.0
Sumanth Chinthagunta
 
PDF
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Marcin Mieszek
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
PDF
Angular Weekend
Troy Miles
 
PPTX
Angular2 for Beginners
Oswald Campesato
 
PDF
Reactive microservices with Micronaut - Greach 2018
Alvaro Sanchez-Mariscal
 
PPTX
Angular beans
Bessem Hmidi
 
PPTX
Angular js 2
Ran Wahle
 
PDF
Introduction to Spring Boot
Trey Howard
 
PDF
Play Framework workshop: full stack java web app
Andrew Skiba
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Intro to Retrofit 2 and RxJava2
Fabio Collini
 
Java Intro: Unit1. Hello World
Yakov Fain
 
Overview of the AngularJS framework
Yakov Fain
 
Test Driven Development with JavaFX
Hendrik Ebbers
 
Serverless functions with Micronaut
Alvaro Sanchez-Mariscal
 
AngularJS Unit Test
Chiew Carol
 
React state management with Redux and MobX
Darko Kukovec
 
The Many Ways to Test Your React App
All Things Open
 
Single Page Applications with AngularJS 2.0
Sumanth Chinthagunta
 
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Marcin Mieszek
 
Spring Boot
Jiayun Zhou
 
Spring boot Introduction
Jeevesh Pandey
 
Angular Weekend
Troy Miles
 
Angular2 for Beginners
Oswald Campesato
 
Reactive microservices with Micronaut - Greach 2018
Alvaro Sanchez-Mariscal
 
Angular beans
Bessem Hmidi
 
Angular js 2
Ran Wahle
 
Introduction to Spring Boot
Trey Howard
 
Play Framework workshop: full stack java web app
Andrew Skiba
 
Ad

Viewers also liked (12)

PDF
Live chym kysubrse vs toidicodedao
Huy Hoàng Phạm
 
PDF
Luận văn tìm hiểu Spring
An Nguyen
 
PPTX
Sinh viên IT học và làm gì để không thất nghiệp
Huy Hoàng Phạm
 
PPT
Lap trinh java hieu qua
Lê Anh
 
PDF
Từ Gà Đến Pro Git và GitHub trong 60 phút
Huy Hoàng Phạm
 
PDF
Spring mvc
Ba Big
 
PPTX
Spring mvc
nagarajupatangay
 
PDF
Từ Sinh Viên IT tới Lập Trình Viên
Huy Hoàng Phạm
 
PPTX
Hành trình trở thành web đì ve lốp pơ
Huy Hoàng Phạm
 
PPTX
Effective Java
Brice Argenson
 
PPTX
Effective java
Emprovise
 
PDF
Effective java
Haeil Yi
 
Live chym kysubrse vs toidicodedao
Huy Hoàng Phạm
 
Luận văn tìm hiểu Spring
An Nguyen
 
Sinh viên IT học và làm gì để không thất nghiệp
Huy Hoàng Phạm
 
Lap trinh java hieu qua
Lê Anh
 
Từ Gà Đến Pro Git và GitHub trong 60 phút
Huy Hoàng Phạm
 
Spring mvc
Ba Big
 
Spring mvc
nagarajupatangay
 
Từ Sinh Viên IT tới Lập Trình Viên
Huy Hoàng Phạm
 
Hành trình trở thành web đì ve lốp pơ
Huy Hoàng Phạm
 
Effective Java
Brice Argenson
 
Effective java
Emprovise
 
Effective java
Haeil Yi
 
Ad

Similar to Reactive Streams and RxJava2 (20)

PDF
Reactive Programming in Java and Spring Framework 5
Richard Langlois P. Eng.
 
PDF
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
PDF
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
PDF
Building Scalable Stateless Applications with RxJava
Rick Warren
 
PPTX
Realtime Statistics based on Apache Storm and RocketMQ
Xin Wang
 
PDF
Springone2gx 2014 Reactive Streams and Reactor
Stéphane Maldini
 
PPTX
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
StreamNative
 
PDF
Reactive database access with Slick3
takezoe
 
PPTX
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
PPTX
Functional reactive programming
Araf Karsh Hamid
 
PDF
Reactive systems
Naresh Chintalcheru
 
PPTX
Reactive Streams - László van den Hoek
RubiX BV
 
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Rick Hightower
 
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Rick Hightower
 
PPTX
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
PDF
Fast Streaming into Clickhouse with Apache Pulsar
Timothy Spann
 
PDF
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
PDF
Troubleshooting Kafka's socket server: from incident to resolution
Joel Koshy
 
PDF
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
HostedbyConfluent
 
PDF
Multi-service reactive streams using Spring, Reactor, RSocket
Stéphane Maldini
 
Reactive Programming in Java and Spring Framework 5
Richard Langlois P. Eng.
 
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Realtime Statistics based on Apache Storm and RocketMQ
Xin Wang
 
Springone2gx 2014 Reactive Streams and Reactor
Stéphane Maldini
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
StreamNative
 
Reactive database access with Slick3
takezoe
 
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
Functional reactive programming
Araf Karsh Hamid
 
Reactive systems
Naresh Chintalcheru
 
Reactive Streams - László van den Hoek
RubiX BV
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Rick Hightower
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Rick Hightower
 
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Fast Streaming into Clickhouse with Apache Pulsar
Timothy Spann
 
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
Troubleshooting Kafka's socket server: from incident to resolution
Joel Koshy
 
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
HostedbyConfluent
 
Multi-service reactive streams using Spring, Reactor, RSocket
Stéphane Maldini
 

More from Yakov Fain (14)

PDF
Type script for_java_dev_jul_2020
Yakov Fain
 
PDF
TypeScript for Java Developers
Yakov Fain
 
PDF
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Angular 4 for Java Developers
Yakov Fain
 
PDF
Angular 2 for Java Developers
Yakov Fain
 
PDF
Dart for Java Developers
Yakov Fain
 
PDF
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
PDF
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
PDF
Seven Versions of One Web Application
Yakov Fain
 
PDF
Running a Virtual Company
Yakov Fain
 
PDF
Princeton jug git_github
Yakov Fain
 
PDF
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
 
PDF
Surviving as a Professional Software Developer
Yakov Fain
 
PDF
Becoming a professional software developer
Yakov Fain
 
Type script for_java_dev_jul_2020
Yakov Fain
 
TypeScript for Java Developers
Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
Angular 4 for Java Developers
Yakov Fain
 
Angular 2 for Java Developers
Yakov Fain
 
Dart for Java Developers
Yakov Fain
 
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
Seven Versions of One Web Application
Yakov Fain
 
Running a Virtual Company
Yakov Fain
 
Princeton jug git_github
Yakov Fain
 
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
 
Surviving as a Professional Software Developer
Yakov Fain
 
Becoming a professional software developer
Yakov Fain
 

Recently uploaded (20)

DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Doc9.....................................
SofiaCollazos
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
This slide provides an overview Technology
mineshkharadi333
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Software Development Company | KodekX
KodekX
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 

Reactive Streams and RxJava2

  • 1. Reactive Streams and RxJava2 Yakov Fain, Farata Systems
 
 yfain
  • 2. About myself • Solutions Architect at Farata Systems • Java Champion • Latest book:
 “Angular 2 Development with TypeScript”

  • 3. “If I had asked people what they wanted, they would have said faster horses”
 
 Henry Ford

  • 4. Synchronous vs asynchronous • Synchronous programming is straightforward • Asynchronous programming dramatically increases complexity
  • 5. Challenges in async programming • Handling failed async requests • Chaining async calls • The user already closed the view • Switching threads to update UI
  • 6. and more challenges • Avoiding writing blocking code in a multi-threaded app • Several consumers • Composable functions • Killing a pending Http request
  • 7. Backpressure Subscriber
 Sammy A publisher generates more data than a subscriber can process Publisher
  • 8. Examples of backpressure • The stock price changes 100 times a second • Accelerometer produces 50 signals a second • Iteration through a JDBC result set (rxjava-jdbc; rxjava2-jdbc) • A user drags the mouse to draw a curve. Can’t apply back pressure.
  • 9. Reactive Apps • The data is processed as streams • Message-driven: notifications • Resilient: stay alive in case of failures • Data flows through your app’s algorithms • Hide complexity of multi-threading
  • 10. Reactive Streams • A spec for async stream processing with non-blocking backpressure
 
 http://www.reactive-streams.org
 • Reactive Streams interfaces for JVM 
 
 https://github.com/reactive-streams/reactive-streams-jvm • Reactive Streams-based products: 
 
 RxJava2, Java 9 Flow APIs, Reactor 3, Akka Stream, MongoDB, Vert.x …
  • 13. Reactive Streams: Java interfaces backpressure
 support
  • 14. Reactive Streams: Java interfaces backpressure
 support
  • 15. Main RxJava2 players • Observable or Flowable - producers of data • Observer or Subscriber - consumers of data • Subject or Processor - implements both producer and consumer • Operator - en-route data transformation • Scheduler - multi-threading support
  • 16. Main Publishers and Subscribers in RxJava2 Observable
 no backpressure support 
 public interface Observer<T> {
 void onSubscribe(Disposable var1);
 
 void onNext(T var1);
 
 void onError(Throwable var1);
 
 void onComplete();
 } Publisher Subscriber Not from 
 Reactive Streams
  • 17. Observable
 no backpressure support Flowable
 with backpressure support public interface Observer<T> {
 void onSubscribe(Disposable var1);
 
 void onNext(T var1);
 
 void onError(Throwable var1);
 
 void onComplete();
 } public interface Subscriber<T> {
 void onSubscribe(Subscription var1);
 
 void onNext(T var1);
 
 void onError(Throwable var1);
 
 void onComplete();
 } Not from 
 Reactive Streams From 
 Reactive Streams Main publishers and subscribers in RxJava2 Publisher Subscriber
  • 18. Creating an Observable • Observable.create() • Observable.fromArray() • Observable.fromIterable() • Observable.fromCallable() • Observable.fromFuture() • Observable.range() • Observable.just() Observable.create(subscriber -> { int totalBeers = beerStock.size(); for (int i = 0; i < totalBeers; i++) {
 // synchronous push subscriber.onNext(beerStock.get(i)); } subscriber.onComplete(); });
  • 19. Observable<Beer> observableBeer = Observable.create(/* data source */); observableBeer
 .skip(1)
 .take(3)
 .filter(beer -> "USA".equals(beer.country))
 .map(beer -> beer.name + ": $" + beer.price)
 .subscribe(
 beer -> System.out.println(beer),
 
 err -> System.out.println(err),
 
 () -> System.out.println("Streaming is complete”),
 
 disposable -> System.out.println( 
 "Someone just subscribed to the beer stream!!!”)
 );
 ); Observable push O b s e r v e r Subscription
  • 20. Creating an Observer and subscribing Observable<Beer> beerData = BeerServer.getData(); // returns an Observable
 
 Observer beerObserver = new Observer<Beer>() {
 
 public void onSubscribe(Disposable d) {
 System.out.println( " !!! Someone just subscribed to the bear stream!!! ");
 
 // If the subscriber is less than 21 year old, cancel subscription
 // d.dispose();
 }
 
 public void onNext(Beer beer) {
 System.out.println(beer);
 }
 
 public void onError(Throwable throwable) {
 System.err.println("In Observer.onError(): " + throwable.getMessage());
 }
 
 public void onComplete() {
 System.out.println("*** The stream is over ***");
 }
 };
 
 beerData
 .subscribe(beerObserver); // Streaming starts here
  • 21. Subscription subscription = Observable.create(new Observable.OnSubscribe<Response>() {
 OkHttpClient client = new OkHttpClient();
 
 @Override public void call(Subscriber<? super Response> subscriber) { // invoked on subscription try { Response response = client.newCall( // prepare the call for future execution new Request.Builder().url(“http://localhost:8080/beers“) .build()) .execute(); // use enqueue() for async requests 
 subscriber.onNext(response);
 
 subscriber.onComplete(); 
 if (!response.isSuccessful()) { subscriber.onError(new Exception(“Can’t get beers”)); } } catch (IOException e) { subscriber.onError(e); } } })
 .subscribe(...); // pass Observer; use observeOn/SubscribeOn to switch threads Pushing HTTP responses https://square.github.io/okhttp
  • 22. Controlling the flow with request() request(1); request(1);
  • 23. Handling backpressure Publisher Subscriber request(1) request(3) … request() is non-blocking onNext(value1) onNext(value2) onNext(value3) onNext(value4)
  • 27. Creating a Flowable • Flowable.create() • Flowable.fromArray() • Flowable.fromIterable() • Flowable.fromCallable() • Flowable.empty() • Flowable.range() • Flowable.just()
  • 29. Requesting data from Flowable public class FlowableRange {
 
 static DisposableSubscriber<Integer> subscriber;
 
 public static void main(String[] args) {
 
 subscriber = new DisposableSubscriber<Integer>() {
 
 public void onStart() {
 request(5);
 
 while (true){ // Emulate 1-sec processing
 try {
 Thread.sleep(1000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 request(1);
 }
 }
 
 public void onNext(Integer t) {
 System.out.println("processing "+ t);
 if (t==8) { // just to demo unsubscribing
 subscriber.dispose();
 }
 }
 
 public void onError(Throwable thr) {
 System.err.println("In onError(): " + thr.getMessage()); 
 }
 
 public void onComplete() {
 System.out.println("Done");
 }
 };
 
 Flowable.range(1, 10)
 .subscribe(subscriber);
 }
 }
  • 30. Demo 
 1. FlowableRange
 2. BeerClientFlowable Code samples: https://github.com/yfain/rxjava2
  • 31. An Operator Observable Observable A transforming
 function observableBeer
 .filter(b -> "USA".equals(b.country)) Docs: http://reactivex.io/documentation/operators
  • 32. QUIZ: What value(s) this observable emits? Observable
 .just(5, 9, 10) // emits 5, 9, 10
 
 .filter(i -> i % 3 > 0)
 
 .map(n -> "$" + n * 10)
 
 .filter(s -> s.length() < 4);
  • 33. Observable
 .just(5, 9, 10) // emits 5, 9, 10
 
 .filter(i -> i % 3 > 0)
 
 .map(n -> "$" + n * 10)
 
 .filter(s -> s.length() < 4) 
 .subscribe(System.out::println);
  • 37. zip: combining observables of different types
  • 40. Types of Observables Hot Cold Push Produce a steam even
 if no-one cares r Produce a stream when 
 someone asks for it ✔
  • 41. Hot Observables • Mouse events • Publishing stock prices • An accelerometer in a smartphone
  • 43. Turning a cold observable into hot ConnectableObservable<Long> numbers = (ConnectableObservable<Long>) Observable
 .interval(1, TimeUnit.SECONDS) // generate seq numbers every second
 .publish(); // make it hot
 
 numbers.connect(); // creates an internal subscriber to start producing data
 numbers.subscribe(n ->System.out.println("First subscriber: "+ n ));
 
 Thread.sleep(3000);
 
 numbers.subscribe(n ->System.out.println(" Second subscriber: "+ n ));

  • 46. Concurrency with Schedulers • subscribeOn(strategy) - run Observable in a separate thread: 
 Operations with side effects like files I/O;
 Don’t hold off the UI thread
 • observeOn(strategy) - run Observer in a separate thread,
 Update Swing UI on the Event Dispatch Thread
 Update Android UI on the Main thread
  • 47. Multi-threading strategies • Schedulers.computation() - for computations: # of threads <= # of cores • Schedulers.io() - for long running communications; backed by a thread pool • Schedulers.newThread() - new thread for each unit of work • Schedulers.from(Executor) - a wrapper for Java Executor • Schedulers.trampoline() - queues the work on the current thread • AndroidSchedulers.mainThread() - handle data on the main thread (RxAndroid)
  • 48. Switching threads Operator1() Operator2() ObserveOn() Observable Subscriber Thread 1 Thread 2 subscribeOn() observeOn()
  • 49. Multi-threaded processing with flatMap() Operator1() Operator2() flatMap() Observable Subscriber Thread 1 Observable/Thr2 Observable/Thr3 Observable/ThrN Spawn a separate thread for each observable …
  • 50. Turning a value into
 an observable Observable.range(1, 1000) .flatMap(n->Observable.just(n)
 .subscribeOn(Schedulers.computation()))
 .map(n->n*2)
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(myView.update()); Subscribing to each observable on the computation thread Switching to the main thread Updating the UI
  • 52. Parallel operations with ParallelFlowabe • Parallel execution of some operators
 • The source sequence is dispatched into N parallel “rails” • runOn() —-> sequential() is more efficient fork/join than flatMap()
 • Each rail can spawn multiple async threads with Schedulers
  • 53. Parallel Execution int numberOfRails = 4; // can query #processors with parallelism()
 
 ParallelFlowable
 .from(Flowable.range(1, 10), numberOfRails)
 .runOn(Schedulers.computation())
 .map(i -> i * i)
 .filter(i -> i % 3 == 0)
 .sequential()
 .subscribe(System.out::println); Tasks run simultaneously on different CPUs or computers. ParallelFlowableRange.java
  • 54. Summary • Observable: no backpressure support • Flowable: backpressure support • Operators can be chained • flatmap() used for handling observable of observables • Schedulers support multi-threading • subscribeOn()/observeOn() - switching between threads • ParallelFlowable - initiate parallel processing
  • 55. Links • Slides: http://bit.ly/2q3Ovt4 • Code samples: 
 https://github.com/yfain/rxjava2 • Our company: faratasystems.com • Blog: yakovfain.com • Twitter: @yfain