SlideShare a Scribd company logo
1 of 55
Download to read offline
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

What's hot

Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov Fain
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobXDarko Kukovec
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Sumanth Chinthagunta
 
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5Marcin Mieszek
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
Reactive microservices with Micronaut - Greach 2018
Reactive microservices with Micronaut - Greach 2018Reactive microservices with Micronaut - Greach 2018
Reactive microservices with Micronaut - Greach 2018Alvaro Sanchez-Mariscal
 
Angular js 2
Angular js 2Angular js 2
Angular js 2Ran Wahle
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
Play Framework workshop: full stack java web app
Play Framework workshop: full stack java web appPlay Framework workshop: full stack java web app
Play Framework workshop: full stack java web appAndrew Skiba
 

What's hot (20)

Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Serverless functions with Micronaut
Serverless functions with MicronautServerless functions with Micronaut
Serverless functions with Micronaut
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobX
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
 
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
Mobx for Dummies - Yauheni Nikanowich - React Warsaw #5
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Reactive microservices with Micronaut - Greach 2018
Reactive microservices with Micronaut - Greach 2018Reactive microservices with Micronaut - Greach 2018
Reactive microservices with Micronaut - Greach 2018
 
Angular beans
Angular beansAngular beans
Angular beans
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Play Framework workshop: full stack java web app
Play Framework workshop: full stack java web appPlay Framework workshop: full stack java web app
Play Framework workshop: full stack java web app
 

Viewers also liked

Live chym kysubrse vs toidicodedao
Live chym kysubrse vs toidicodedaoLive chym kysubrse vs toidicodedao
Live chym kysubrse vs toidicodedaoHuy Hoàng Phạm
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu SpringAn Nguyen
 
Sinh viên IT học và làm gì để không thất nghiệp
Sinh viên IT học và làm gì để không thất nghiệpSinh viên IT học và làm gì để không thất nghiệp
Sinh viên IT học và làm gì để không thất nghiệpHuy Hoàng Phạm
 
Lap trinh java hieu qua
Lap trinh java hieu quaLap trinh java hieu qua
Lap trinh java hieu quaLê Anh
 
Từ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phútTừ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phútHuy Hoàng Phạm
 
Spring mvc
Spring mvcSpring mvc
Spring mvcBa Big
 
Từ Sinh Viên IT tới Lập Trình Viên
Từ Sinh Viên IT tới Lập Trình ViênTừ Sinh Viên IT tới Lập Trình Viên
Từ Sinh Viên IT tới Lập Trình ViênHuy Hoàng Phạm
 
Hành trình trở thành web đì ve lốp pơ
Hành trình trở thành web đì ve lốp pơHành trình trở thành web đì ve lốp pơ
Hành trình trở thành web đì ve lốp pơHuy Hoàng Phạm
 
Effective java
Effective javaEffective java
Effective javaEmprovise
 
Effective java
Effective javaEffective java
Effective javaHaeil Yi
 

Viewers also liked (12)

Live chym kysubrse vs toidicodedao
Live chym kysubrse vs toidicodedaoLive chym kysubrse vs toidicodedao
Live chym kysubrse vs toidicodedao
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu Spring
 
Sinh viên IT học và làm gì để không thất nghiệp
Sinh viên IT học và làm gì để không thất nghiệpSinh viên IT học và làm gì để không thất nghiệp
Sinh viên IT học và làm gì để không thất nghiệp
 
Lap trinh java hieu qua
Lap trinh java hieu quaLap trinh java hieu qua
Lap trinh java hieu qua
 
Từ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phútTừ Gà Đến Pro Git và GitHub trong 60 phút
Từ Gà Đến Pro Git và GitHub trong 60 phút
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Từ Sinh Viên IT tới Lập Trình Viên
Từ Sinh Viên IT tới Lập Trình ViênTừ Sinh Viên IT tới Lập Trình Viên
Từ Sinh Viên IT tới Lập Trình Viên
 
Hành trình trở thành web đì ve lốp pơ
Hành trình trở thành web đì ve lốp pơHành trình trở thành web đì ve lốp pơ
Hành trình trở thành web đì ve lốp pơ
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Effective java
Effective javaEffective java
Effective java
 
Effective java
Effective javaEffective java
Effective java
 

Similar to Reactive Streams and RxJava2

Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Richard Langlois P. Eng.
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsKevin Webber
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorVMware Tanzu
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Realtime Statistics based on Apache Storm and RocketMQ
Realtime Statistics based on Apache Storm and RocketMQRealtime Statistics based on Apache Storm and RocketMQ
Realtime Statistics based on Apache Storm and RocketMQXin Wang
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorStéphane Maldini
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteStreamNative
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3takezoe
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programmingAraf Karsh Hamid
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den HoekRubiX BV
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)Rick Hightower
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)Rick Hightower
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaKasun Indrasiri
 
Fast Streaming into Clickhouse with Apache Pulsar
Fast Streaming into Clickhouse with Apache PulsarFast Streaming into Clickhouse with Apache Pulsar
Fast Streaming into Clickhouse with Apache PulsarTimothy Spann
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsKonrad Malawski
 
Troubleshooting Kafka's socket server: from incident to resolution
Troubleshooting Kafka's socket server: from incident to resolutionTroubleshooting Kafka's socket server: from incident to resolution
Troubleshooting Kafka's socket server: from incident to resolutionJoel Koshy
 
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, NutanixGuaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, NutanixHostedbyConfluent
 
Multi-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocketMulti-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocketStéphane Maldini
 

Similar to Reactive Streams and RxJava2 (20)

Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Realtime Statistics based on Apache Storm and RocketMQ
Realtime Statistics based on Apache Storm and RocketMQRealtime Statistics based on Apache Storm and RocketMQ
Realtime Statistics based on Apache Storm and RocketMQ
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and Reactor
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
 
Reactive systems
Reactive systemsReactive systems
Reactive systems
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Fast Streaming into Clickhouse with Apache Pulsar
Fast Streaming into Clickhouse with Apache PulsarFast Streaming into Clickhouse with Apache Pulsar
Fast Streaming into Clickhouse with Apache Pulsar
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka Streams
 
Troubleshooting Kafka's socket server: from incident to resolution
Troubleshooting Kafka's socket server: from incident to resolutionTroubleshooting Kafka's socket server: from incident to resolution
Troubleshooting Kafka's socket server: from incident to resolution
 
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, NutanixGuaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
Guaranteed Event Delivery with Kafka and NodeJS | Amitesh Madhur, Nutanix
 
Multi-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocketMulti-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocket
 

More from Yakov Fain

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Yakov Fain
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsYakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTYakov Fain
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowYakov Fain
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web ApplicationYakov Fain
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual CompanyYakov Fain
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_githubYakov Fain
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software DeveloperYakov Fain
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developerYakov Fain
 

More from Yakov Fain (14)

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot apps
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_github
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software Developer
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developer
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

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