SlideShare a Scribd company logo
1 of 77
Download to read offline
Reactive Thinking in Java

with RxJava2
Yakov Fain, Farata Systems



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

“Angular 2 Development with TypeScript”

The problem with not being reactive
int a1 = 2;

int b1 = 4;



int c1 = a1 + b1; // c1 = 6



int a1 = 2;

int b1 = 4;



int c1 = a1 + b1; // c1 = 6



a1 = 55; // c1 = 6;

b1 = 20; // c1 = 6;

The problem with not being reactive
A famous reactive solution
But we face more challenges
• An async request to a server failed later
• You need to chain multiple async calls
• An async response came back, but the user already moved
to a different view
• An async request was executed on a thread A, but the UI
must updated on a main thread
• Allocating a thread to each async request is expensive
• How to avoid blocking code in a multi-threaded app?
and even more challenges
• The same stream has to be processed by several consumers
• The producer pushes the data that should flow through
several composable functions
• Mobile device. Slow connection. An Http request is pending,
but the user made another one. How to kill the pending
request?
• The publisher generates data faster than a consumer can
handle
Backpressure
Publisher Subscriber
Publisher generates more data than subscriber can (or want)
process
Reactive Apps
• The data is processed as streams and not via iterating over
the in-memory data
• Message-driven: components communicate via direct notifications
• A stream can be handled by one or more composable
operators (functions).
• Resilient: stay responsive in case of failures
• The data flows through your app’s algorithm
• Hide complexity of multi-threading
Reactive Streams
• Reactive Streams is 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, MongoDB, Vert.x …
Reactive Streams: Java interfaces
1
2
3
4
backpressure

support
Examples of backpressure
• The stock price may change hundreds times a second, but the
user’s display should change once a second.
• Android accelerometer produces 50 readings a second, but
your app should react to one signal per 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.
Handling backpressure
Publisher Subscriber
request(1)
request(3)
…
Even if the publisher is slow and the data is not be available, 

the request() doesn’t block.
onNext(value1)
onNext(value2)
onNext(value3)
onNext(value4)
Rx libraries
• RxJava (end of life: March 2018)

RxAndroid, RxJavaFX, RxSwing
• RxJava2
• Other Rx libraries:

Rx.NET, RxCpp, RxJS, Rx.rb, Rx.py, RxSwift, RxScala, RxPHP
http://reactivex.io
Main RxJava2 players
• Observable or Flowable - producers of data
• Observer or Subscriber - consumers of data
• Subject or Processor - implements 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
beers.forEach(beer -> {

if ("USA".equals(beer.country)){

americanBeers.add(beer);

}

});
Java Iterable: a pull
beers.stream()

.skip(1)

.limit(3)

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

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

.forEach(beer -> System.out.println(beer));

Java 8 Stream API: a pull
A pull with a tool is still a pull
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!!!”)

);

);
Rx Observable: a push
O
b
s
e
r
v
e
r
Subscribtion
Adding RxJava2 to your project
Or find rxjava2 and reactive-streams jars on search.maven.org
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>x.y.z</version>
</dependency>
Maven:
Creating an Observable
• Observable.create()
• Observable.fromArray()
• Observable.fromIterable()
• Observable.fromCallable()
• Observable.fromFuture()
• Observable.range()
• Observable.just()
Synchronous push
List<Beer> beerStock = new ArrayList<>();
…
Observable.create(subscriber -> {



int totalBeers = beerStock.size();

for (int i = 0; i < totalBeers; i++) {



subscriber.onNext(beerStock.get(i));

}



subscriber.onComplete();
…
Observable.create(subscriber -> {



myHttpClient.getBeers(new Callback(){

public void onResponse(Response res){

subscriber.onNext(res.body().string());
subscriber.onComplete(); 

}
public void onFailure (IOException e){
subscriber.onError(e);
}
}
});
Asynchronous push
Creating an Observer and subscribing
Observable<Beer> beerData = BeerServer.getData(); // returns 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
Demo 

BeerClient
Specialized Observables
• Single - Emits a exactly one item or sends an error
• Completable - Emits either complete or error - no data

Any response is better than no response!
• Maybe - Either emits exactly one item, or completes with 

no items, or sends an error
Controlling the flow with request()
request(1); request(1);
Flowables and backpressure strategies
• BackpressureStrategy.BUFFER - process what you can; put the rest in the buffer 

until the next request.
• BackpressureStrategy.DROP - process what you can; ignore the rest until the 

next request.
• BackpressureStrategy.LATEST - process what you can; ignore the rest until the 

next request, but cache the latest element

• BackpressureStrategy.MISSING - don’t apply backpressure; if consumer can’t keep

up, it may throw MissingBackpressureException or IllegalStateException
• BackpressureStrategy.ERROR - apply backpressure; if consumer can’t keep up,

it throws MissingBackpressureException
The BUFFER strategy
BackpressureStrategy.BUFFER
BackpressureStrategy.DROP
The DROP strategy
BackpressureStrategy.LATEST
The LATEST strategy
Creating a Flowable
• Flowable.create()
• Flowable.fromArray()
• Flowable.fromIterable()
• Flowable.fromCallable()
• Flowable.empty()
• Flowable.range()
• Flowable.just()
Creating a Flowable
• Flowable.create()
• Flowable.fromArray()
• Flowable.fromIterable()
• Flowable.fromCallable()
• Flowable.fromFuture()
• Flowable.empty()
• Flowable.range()
• Flowable.just()
myObservable

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

.create(beerEmitter ->{…},

BackpressureStrategy.BUFFER)
Create
Convert
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 some 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) {

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);

}

}
Demos 

1. FlowableRange

2. BeerClientFlowable
FP: a pure function
• Produces no side effects
• The same input always results in the same output
• Doesn’t modify the input
• Doesn’t rely on the external state
Sharing state require locks, may cause race conditions, and
complicates programming
FP: a higher-order function
• Can take one or more functions as argument(s)
• Can return a function
An Operator
Observable Observable
A transforming

function
An Operator
Observable Observable
A transforming

function
observableBeer

.filter(b -> "USA".equals(b.country))
An Operator
Observable Observable
A transforming

function
A higher-order function
observableBeer

.filter(b -> "USA".equals(b.country))
A pure function
map
filter
RX: the data moves across your algorithm
Observable
Operator
Observable
Operator
Observable
Operator
Observable
Operator
QUIZ: What value(s) this observable will emit?
Observable

.just(5, 9, 10)

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

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

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


Observable

.just(5, 9, 10)

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

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

.filter(s -> s.length() < 4)
.subscribe(System.out::println);
QUIZ: What value(s) this observable will emit?
Functions with side effects
• doOnNext()
• doOnError()
• doOnComplete()
• doOnEach()
• doOnSubscribe()
• doOnDispose()
Affect environment outside the function.
Error reporting
Observer Observable
onNext()
onError()
onComplete()
When the Observable or Flowable throws an exception it still
invokes Observer.onError() or Subscriber.onError()
Error-handling operators
• onError() kills the subscription
• retryWhen() - intercept and analyze the error; resubscribe
• retryUntil() - retry until a certain condition is true
• onErrorResumeNext() - used for failover to another Observable
Demo 

BeerClientWithFailover
Composing observables
concat: combining observables of the
same type in order
merge: combining observables of the same type
zip: combining observables of different types
flatMap
.flatMap()Observable
Can spawn multiple threads
Demo 

composingObservables/ObservableDrinks
switchMap
Demo 

Angular client, weather app
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
• Scedulers.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
With flatMap() it’s easy to spawn a different thread to 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
Displaying the result 

on the main thread
Demo 

schedulers/SubscribeOnObserveOn

ParallelStreamsRange

ParallelStreams
Parallel operations with ParallelFlowabe
• ParallelFlowable allows parallel execution of a few operators
• The source sequence is dispatched into N parallel “rails”
• More efficient forking and joining than with flatMap()

runOn() —-> sequential()
• Each rail can spawn multiple async threads with Schedulers
Parallel operations with ParallelFlowabe
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);
Demo: ParallelFlowableRange
Types of Observables
Hot Cold
Push
Produce the steam even

if no-one cares
r
Produce the stream when 

someone asks for it
✔
Hot Observables
• Mouse-generated events are emitted even if there are no subscribers
• Button clicks
• Stock prices are being published on a server socket regardless if any
client is connected
• A sensor in a mobile device sends signals even if no apps are
handling them
Making observables hot
Using publish() and connect()
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
Summary
• Observable: no backpressue; no reactive streams spec
• Flowable: backpressure; reactive streams spec
• Operators can be chained
• flatmap() used for handling observable of observables
• Schedulers support multi-threading
• subscribeOn()/observeOn() - switching between threads
• ParallelFlowable - initiate parallel processing
• Observables can be hot or cold
Thank you!
• Code samples: 

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


More Related Content

What's hot

Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6William Marques
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React EcosystemFITC
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application TestingTroy Miles
 
Angular js 2
Angular js 2Angular js 2
Angular js 2Ran Wahle
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Hsuan Fu Lien
 
An afternoon with angular 2
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2Mike Melusky
 
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
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core conceptsCodemotion
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkCodemotion
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Ahmed Moawad
 
Automated Testing in Angular Slides
Automated Testing in Angular SlidesAutomated Testing in Angular Slides
Automated Testing in Angular SlidesJim Lynch
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Codemotion
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMJimit Shah
 

What's hot (20)

Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React Ecosystem
 
Angular 5
Angular 5Angular 5
Angular 5
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Angularjs
AngularjsAngularjs
Angularjs
 
Angular 4
Angular 4Angular 4
Angular 4
 
Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)
 
An afternoon with angular 2
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2
 
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
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
 
Automated Testing in Angular Slides
Automated Testing in Angular SlidesAutomated Testing in Angular Slides
Automated Testing in Angular Slides
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 

Similar to Reactive Thinking in Java with RxJava2

Reactive java programming for the impatient
Reactive java programming for the impatientReactive java programming for the impatient
Reactive java programming for the impatientGrant Steinfeld
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxInexture Solutions
 
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
 
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
 
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay PlatonovSenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay PlatonovSencha
 
Introduction to Akka Streams
Introduction to Akka StreamsIntroduction to Akka Streams
Introduction to Akka StreamsKnoldus Inc.
 
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
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
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
 
Socket applications
Socket applicationsSocket applications
Socket applicationsJoão Moura
 
Distributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqDistributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqRuben Tan
 
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 StreamsDean Wampler
 
Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...Lori MacVittie
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and ReduxMaxime Najim
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx javaCongTrung Vnit
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lightbend
 
Raising ux bar with offline first design
Raising ux bar with offline first designRaising ux bar with offline first design
Raising ux bar with offline first designKyrylo Reznykov
 

Similar to Reactive Thinking in Java with RxJava2 (20)

Reactive java programming for the impatient
Reactive java programming for the impatientReactive java programming for the impatient
Reactive java programming for the impatient
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFlux
 
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
 
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
 
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay PlatonovSenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
 
Introduction to Akka Streams
Introduction to Akka StreamsIntroduction to Akka Streams
Introduction to Akka Streams
 
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
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and Reactor
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Distributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqDistributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromq
 
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
 
Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and Redux
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
 
Intro to sbt-web
Intro to sbt-webIntro to sbt-web
Intro to sbt-web
 
Raising ux bar with offline first design
Raising ux bar with offline first designRaising ux bar with offline first design
Raising ux bar with offline first design
 

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
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov 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
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov 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
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov 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 (16)

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
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
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
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
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

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Reactive Thinking in Java with RxJava2

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

  • 3. The problem with not being reactive int a1 = 2;
 int b1 = 4;
 
 int c1 = a1 + b1; // c1 = 6
 

  • 4. int a1 = 2;
 int b1 = 4;
 
 int c1 = a1 + b1; // c1 = 6
 
 a1 = 55; // c1 = 6;
 b1 = 20; // c1 = 6;
 The problem with not being reactive
  • 5. A famous reactive solution
  • 6. But we face more challenges • An async request to a server failed later • You need to chain multiple async calls • An async response came back, but the user already moved to a different view • An async request was executed on a thread A, but the UI must updated on a main thread • Allocating a thread to each async request is expensive • How to avoid blocking code in a multi-threaded app?
  • 7. and even more challenges • The same stream has to be processed by several consumers • The producer pushes the data that should flow through several composable functions • Mobile device. Slow connection. An Http request is pending, but the user made another one. How to kill the pending request? • The publisher generates data faster than a consumer can handle
  • 8. Backpressure Publisher Subscriber Publisher generates more data than subscriber can (or want) process
  • 9. Reactive Apps • The data is processed as streams and not via iterating over the in-memory data • Message-driven: components communicate via direct notifications • A stream can be handled by one or more composable operators (functions). • Resilient: stay responsive in case of failures • The data flows through your app’s algorithm • Hide complexity of multi-threading
  • 10. Reactive Streams • Reactive Streams is 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, MongoDB, Vert.x …
  • 11. Reactive Streams: Java interfaces 1 2 3 4 backpressure
 support
  • 12. Examples of backpressure • The stock price may change hundreds times a second, but the user’s display should change once a second. • Android accelerometer produces 50 readings a second, but your app should react to one signal per 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.
  • 13. Handling backpressure Publisher Subscriber request(1) request(3) … Even if the publisher is slow and the data is not be available, 
 the request() doesn’t block. onNext(value1) onNext(value2) onNext(value3) onNext(value4)
  • 14. Rx libraries • RxJava (end of life: March 2018)
 RxAndroid, RxJavaFX, RxSwing • RxJava2 • Other Rx libraries:
 Rx.NET, RxCpp, RxJS, Rx.rb, Rx.py, RxSwift, RxScala, RxPHP http://reactivex.io
  • 15. Main RxJava2 players • Observable or Flowable - producers of data • Observer or Subscriber - consumers of data • Subject or Processor - implements 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. beers.forEach(beer -> {
 if ("USA".equals(beer.country)){
 americanBeers.add(beer);
 }
 }); Java Iterable: a pull
  • 19. beers.stream()
 .skip(1)
 .limit(3)
 .filter(beer -> "USA".equals(beer.country))
 .map(beer -> beer.name + ": $" + beer.price) 
 .forEach(beer -> System.out.println(beer));
 Java 8 Stream API: a pull
  • 20. A pull with a tool is still a pull
  • 21. 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!!!”)
 );
 ); Rx Observable: a push O b s e r v e r Subscribtion
  • 22. Adding RxJava2 to your project Or find rxjava2 and reactive-streams jars on search.maven.org <dependency> <groupId>io.reactivex.rxjava2</groupId> <artifactId>rxjava</artifactId> <version>x.y.z</version> </dependency> Maven:
  • 23. Creating an Observable • Observable.create() • Observable.fromArray() • Observable.fromIterable() • Observable.fromCallable() • Observable.fromFuture() • Observable.range() • Observable.just()
  • 24. Synchronous push List<Beer> beerStock = new ArrayList<>(); … Observable.create(subscriber -> {
 
 int totalBeers = beerStock.size();
 for (int i = 0; i < totalBeers; i++) {
 
 subscriber.onNext(beerStock.get(i));
 }
 
 subscriber.onComplete();
  • 25. … Observable.create(subscriber -> {
 
 myHttpClient.getBeers(new Callback(){
 public void onResponse(Response res){
 subscriber.onNext(res.body().string()); subscriber.onComplete(); 
 } public void onFailure (IOException e){ subscriber.onError(e); } } }); Asynchronous push
  • 26. Creating an Observer and subscribing Observable<Beer> beerData = BeerServer.getData(); // returns 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
  • 28. Specialized Observables • Single - Emits a exactly one item or sends an error • Completable - Emits either complete or error - no data
 Any response is better than no response! • Maybe - Either emits exactly one item, or completes with 
 no items, or sends an error
  • 29. Controlling the flow with request() request(1); request(1);
  • 30. Flowables and backpressure strategies • BackpressureStrategy.BUFFER - process what you can; put the rest in the buffer 
 until the next request. • BackpressureStrategy.DROP - process what you can; ignore the rest until the 
 next request. • BackpressureStrategy.LATEST - process what you can; ignore the rest until the 
 next request, but cache the latest element
 • BackpressureStrategy.MISSING - don’t apply backpressure; if consumer can’t keep
 up, it may throw MissingBackpressureException or IllegalStateException • BackpressureStrategy.ERROR - apply backpressure; if consumer can’t keep up,
 it throws MissingBackpressureException
  • 34. Creating a Flowable • Flowable.create() • Flowable.fromArray() • Flowable.fromIterable() • Flowable.fromCallable() • Flowable.empty() • Flowable.range() • Flowable.just()
  • 35. Creating a Flowable • Flowable.create() • Flowable.fromArray() • Flowable.fromIterable() • Flowable.fromCallable() • Flowable.fromFuture() • Flowable.empty() • Flowable.range() • Flowable.just() myObservable
 .toFlowable(BackpressureStrategy.BUFFER) Flowable<Beer> myFlowable
 .create(beerEmitter ->{…},
 BackpressureStrategy.BUFFER) Create Convert
  • 36. 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 some 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) {
 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);
 }
 }
  • 37. Demos 
 1. FlowableRange
 2. BeerClientFlowable
  • 38. FP: a pure function • Produces no side effects • The same input always results in the same output • Doesn’t modify the input • Doesn’t rely on the external state Sharing state require locks, may cause race conditions, and complicates programming
  • 39. FP: a higher-order function • Can take one or more functions as argument(s) • Can return a function
  • 40. An Operator Observable Observable A transforming
 function
  • 41. An Operator Observable Observable A transforming
 function observableBeer
 .filter(b -> "USA".equals(b.country))
  • 42. An Operator Observable Observable A transforming
 function A higher-order function observableBeer
 .filter(b -> "USA".equals(b.country)) A pure function
  • 43. map
  • 45. RX: the data moves across your algorithm
  • 47. QUIZ: What value(s) this observable will emit? Observable
 .just(5, 9, 10)
 .filter(i -> i % 3 > 0)
 .map(n -> "$" + n * 10)
 .filter(s -> s.length() < 4);
  • 48. 
 Observable
 .just(5, 9, 10)
 .filter(i -> i % 3 > 0)
 .map(n -> "$" + n * 10)
 .filter(s -> s.length() < 4) .subscribe(System.out::println); QUIZ: What value(s) this observable will emit?
  • 49. Functions with side effects • doOnNext() • doOnError() • doOnComplete() • doOnEach() • doOnSubscribe() • doOnDispose() Affect environment outside the function.
  • 50. Error reporting Observer Observable onNext() onError() onComplete() When the Observable or Flowable throws an exception it still invokes Observer.onError() or Subscriber.onError()
  • 51. Error-handling operators • onError() kills the subscription • retryWhen() - intercept and analyze the error; resubscribe • retryUntil() - retry until a certain condition is true • onErrorResumeNext() - used for failover to another Observable
  • 54. concat: combining observables of the same type in order
  • 55. merge: combining observables of the same type
  • 56. zip: combining observables of different types
  • 63. 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
  • 64. 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 • Scedulers.trampoline() - queues the work on the current thread • AndroidSchedulers.mainThread() - handle data on the main thread (RxAndroid)
  • 65. Switching threads Operator1() Operator2() ObserveOn() Observable Subscriber Thread 1 Thread 2 subscribeOn() observeOn()
  • 66. Multi-threaded processing with flatMap() Operator1() Operator2() flatMap() Observable Subscriber Thread 1 Observable/Thr2 Observable/Thr3 Observable/ThrN With flatMap() it’s easy to spawn a different thread to each observable …
  • 67. 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 Displaying the result 
 on the main thread
  • 69. Parallel operations with ParallelFlowabe • ParallelFlowable allows parallel execution of a few operators • The source sequence is dispatched into N parallel “rails” • More efficient forking and joining than with flatMap()
 runOn() —-> sequential() • Each rail can spawn multiple async threads with Schedulers
  • 70. Parallel operations with ParallelFlowabe 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); Demo: ParallelFlowableRange
  • 71. Types of Observables Hot Cold Push Produce the steam even
 if no-one cares r Produce the stream when 
 someone asks for it ✔
  • 72. Hot Observables • Mouse-generated events are emitted even if there are no subscribers • Button clicks • Stock prices are being published on a server socket regardless if any client is connected • A sensor in a mobile device sends signals even if no apps are handling them
  • 74. Using publish() and connect() 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 ));

  • 76. Summary • Observable: no backpressue; no reactive streams spec • Flowable: backpressure; reactive streams spec • Operators can be chained • flatmap() used for handling observable of observables • Schedulers support multi-threading • subscribeOn()/observeOn() - switching between threads • ParallelFlowable - initiate parallel processing • Observables can be hot or cold
  • 77. Thank you! • Code samples: 
 https://github.com/yfain/rxjava2 • Our company: faratasystems.com • My blog: yakovfain.com • Twitter: @yfain