SlideShare a Scribd company logo
Reactive Thinking in Java
Yakov Fain, Farata Systems



@yfain
Reactive thinking is not new
Бди!
Козьма Прутков
Reactive thinking is not new
Reactive thinking is not new
The reactive style app
• Message-driven - components communicates via notifications
• Non-imperative - the app logic is coded in async, non-blocking,
composable functions
• The data moves through your app’s algorithm
www.reactivemanifesto.org
Java concurrency
• Blocking I/O is the problem
• Future.get() 

- blocks till all threads are complete
• CompletableFuture.supplyAsync(task).thenAccept(action)
- what if the tasks need to fetch millions of records?
Some open-source Rx libraries
• RxJava
• RxAndroid, RxJavaFX, RxSwing
• Rx.NET, RxCpp, RxJS, Rx.rb, Rx.py, RxSwift,

RxScala, RxPHP
http://reactivex.io
JDK 9 will include reactive streams in java.util.concurrent.Flow
Main RxJava players
• Observable - producer of data
• Observer - consumer of observable sequences
• Subscriber - connects observer with observable
• Operator - en-route data transformation
• Scheduler - multi-threading support
beers.forEach(brr -> {

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

americanBeers.add(brr);

}

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

.skip(1)

.limit(3)

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

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

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

Java 8 Stream: a pull
A fool with a tool is still a fool
Американская народная мудрость
A pull with a tool is still a pull
A fool with a tool is still a fool
Американская народная мудрость
Yakov Fain
Observable is an Iterable inside out
Word Antonym
Iterable Observable
Iterator Observer
Pull Push
Data

Source 

Data Flow
Observable
 Data

Source 

Data Flow
Observable
 Data

Source 

Data Flow
Observable
SubscriberObserver Data

Source 

Data Flow
Observable

onNext()
SubscriberObserver
onError()
onCompleted()
Data

Source 

Data Flow
Event-driven push
Subscribe to messages from Observable and handle them by Observer
Observable
Observer
Subscriber
Observer
Subscriber
push
push
push
Observer
Subscriber
Observable.subscribe(Subscriber)
class Subscriber implements Observer {}
observableBeer

.skip(1)

.take(3)

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

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

.subscribe(

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

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

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

);
Rx Observable: a push
Demo
HelloObservable
Get rxjava.jar on http://search.maven.org
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
An operator is a higher-order function
observableBeer

.filter(b -> "USA".equals(b.country))
pure function
Marble Diagrams
http://rxmarbles.com
Observable map(function){}
Observable filter(function){}
Operator chaining: map and filter
RX: the data moves across your algorithm
Observable
Operator
Observable
Operator
Observable
Operator
Observable
Operator
Creating an Observable
• Observable.create() - returns Observable that can invoke methods on Observer
• Observable.from() - converts an Iterable or Future into Observable
• Observable.fromCallable() - converts a Callable into Observable
• Observable.empty() - returns empty Observable that invokes onCompleted()
• Observable.range() - returns a sequence of integers in the specified range
• Observable.just() - converts up to 10 items into Observable
Demo 

BeerClient
Functions with side effects
• doOnNext()
• doOnError()
• doOnCompleted()
• doOnEach()
• doOnSubscribe()
Affect environment outside the function.
Error Handling
Observer Observable
next
error
completed
Error-handling operators
• Errors sent using onError() kill the subscription

• retryWhen() - intercept, anylize the error, resubscribe

• onErrorResumeNext() - used for failover to another Observable

• onResumeReturn() - returns an app-specific value
Demo 

BeerClientWithFailover
The flatMap() operator
.flatMap()Observable
Demo 

composingObservables/ObservableDrinks
Schedulers
Concurrency with Schedulers
• An observable stream is single-threaded by default
• subscribeOn(strategy) - run Observable in a separate thread
• observeOn(strategy) - run Observer in a separate 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 fo 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
Parallel processing
Operator1() Operator2() flatMap()
Observable
Subscriber
Thread 1
Observable/Thr2
Observable/Thr3
Observable/ThrN
Demo 

schedulers/SubscribeOnObserveOn

schedulers/ParallelStreams
Hot and cold observables
• Cold: emits items only when someone subscribes to it
• Hot: emits items when it’s created regardless if there is a
subscriber or not
Backpressure
• Throttling: sample(), throttleFirst(), debounce()
• Buffers: buffer()
• Window: window(n)
• Reactive pull: Subscriber.request(n)
https://github.com/ReactiveX/RxJava/wiki/Backpressure
Links
• Code samples and slides: 

https://github.com/yfain/rxjava
• Our company: faratasystems.com
• Blog: yakovfain.com
• Twitter:@yfain
 discount code: faindz

More Related Content

PDF
Reactive programming in Angular 2
PPTX
Reactive Programming in Java 8 with Rx-Java
PPTX
The Road To Reactive with RxJava JEEConf 2016
PDF
Reactive Thinking in Java with RxJava2
PPTX
RxJava Applied
PDF
rx-java-presentation
PDF
Building Scalable Stateless Applications with RxJava
PDF
Reactive programming with RxJava
Reactive programming in Angular 2
Reactive Programming in Java 8 with Rx-Java
The Road To Reactive with RxJava JEEConf 2016
Reactive Thinking in Java with RxJava2
RxJava Applied
rx-java-presentation
Building Scalable Stateless Applications with RxJava
Reactive programming with RxJava

What's hot (20)

PDF
Non Blocking I/O for Everyone with RxJava
PDF
Streams, Streams Everywhere! An Introduction to Rx
PPTX
Code generation with javac plugin
PDF
Gatling @ Scala.Io 2013
PDF
Practical RxJava for Android
PPTX
Reactive Java (33rd Degree)
PDF
Rxjava 介紹與 Android 中的 RxJava
PPTX
Reactive Programming on Android - RxAndroid - RxJava
PDF
Concurrency Utilities in Java 8
PDF
The dark side of Akka and the remedy
PDF
RxJava applied [JavaDay Kyiv 2016]
PDF
Angular Weekend
PPTX
Flask & Flask-restx
PDF
Introduction to Retrofit and RxJava
PPTX
Introduction to rx java for android
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PDF
JavaOne 2013: Java 8 - The Good Parts
PDF
RxJava from the trenches
PDF
Reactive Android: RxJava and beyond
PPTX
Reactive Java (GeeCON 2014)
Non Blocking I/O for Everyone with RxJava
Streams, Streams Everywhere! An Introduction to Rx
Code generation with javac plugin
Gatling @ Scala.Io 2013
Practical RxJava for Android
Reactive Java (33rd Degree)
Rxjava 介紹與 Android 中的 RxJava
Reactive Programming on Android - RxAndroid - RxJava
Concurrency Utilities in Java 8
The dark side of Akka and the remedy
RxJava applied [JavaDay Kyiv 2016]
Angular Weekend
Flask & Flask-restx
Introduction to Retrofit and RxJava
Introduction to rx java for android
The Future of Futures - A Talk About Java 8 CompletableFutures
JavaOne 2013: Java 8 - The Good Parts
RxJava from the trenches
Reactive Android: RxJava and beyond
Reactive Java (GeeCON 2014)
Ad

Viewers also liked (20)

PDF
Angular2 Development for Java developers
PPTX
Get along with JHipster
PDF
Hot and spicy Java with Lombok. Live!
PPTX
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
PPTX
Type War: Weak vs Strong [JEEConf 2016]
PDF
What we use to build Android apps at Silicon Straits
PPTX
04 pig data operations
PDF
Spring puzzlers 2
PDF
Play with play!
PPTX
Implement your own profiler with blackjack and fun
PPT
Cours java smi 2007 2008
PDF
Seven Versions of One Web Application
PDF
Dart for Java Developers
PDF
Integrating consumers IoT devices into Business Workflow
PPTX
No Container: a Modern Java Stack with Bootique
PDF
JEEConf. Vanilla java
PDF
Introduction àJava
PDF
Browser-level testing
PPTX
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
PDF
A Post-Apocalyptic sun.misc.Unsafe World
Angular2 Development for Java developers
Get along with JHipster
Hot and spicy Java with Lombok. Live!
Java EE 8: What Servlet 4.0 and HTTP/2 mean to you
Type War: Weak vs Strong [JEEConf 2016]
What we use to build Android apps at Silicon Straits
04 pig data operations
Spring puzzlers 2
Play with play!
Implement your own profiler with blackjack and fun
Cours java smi 2007 2008
Seven Versions of One Web Application
Dart for Java Developers
Integrating consumers IoT devices into Business Workflow
No Container: a Modern Java Stack with Bootique
JEEConf. Vanilla java
Introduction àJava
Browser-level testing
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
A Post-Apocalyptic sun.misc.Unsafe World
Ad

Similar to Reactive Thinking in Java (20)

PPTX
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PDF
React state management with Redux and MobX
PPT
Reactive java programming for the impatient
PDF
Journey into Reactive Streams and Akka Streams
PPTX
RxJava2 Slides
PPT
Reactive programming with examples
PDF
How to Think in RxJava Before Reacting
PPTX
Solve it Differently with Reactive Programming
PPTX
Stream processing from single node to a cluster
PPTX
Reactive Spring 5
PDF
Predictable reactive state management - ngrx
PDF
Java 8 - Project Lambda
ODP
Nexthink Library - replacing a ruby on rails application with Scala and Spray
PDF
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
PDF
Reaching the lambda heaven
PPTX
What’s expected in Spring 5
PDF
Why scala is not my ideal language and what I can do with this
PDF
PDF
Springone2gx 2014 Reactive Streams and Reactor
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Functional Reactive Programming (FRP): Working with RxJS
React state management with Redux and MobX
Reactive java programming for the impatient
Journey into Reactive Streams and Akka Streams
RxJava2 Slides
Reactive programming with examples
How to Think in RxJava Before Reacting
Solve it Differently with Reactive Programming
Stream processing from single node to a cluster
Reactive Spring 5
Predictable reactive state management - ngrx
Java 8 - Project Lambda
Nexthink Library - replacing a ruby on rails application with Scala and Spray
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
Reaching the lambda heaven
What’s expected in Spring 5
Why scala is not my ideal language and what I can do with this
Springone2gx 2014 Reactive Streams and Reactor

More from Yakov Fain (18)

PDF
Type script for_java_dev_jul_2020
PDF
Web sockets in Angular
PDF
Using JHipster for generating Angular/Spring Boot apps
PDF
Using JHipster for generating Angular/Spring Boot apps
PDF
TypeScript for Java Developers
PDF
Reactive Streams and RxJava2
PDF
Using JHipster 4 for generating Angular/Spring Boot apps
PDF
Angular 4 for Java Developers
PDF
Angular 2 for Java Developers
PDF
Overview of the AngularJS framework
PDF
RESTful services and OAUTH protocol in IoT
PDF
Intro to JavaScript
PDF
Java Intro: Unit1. Hello World
PDF
Running a Virtual Company
PDF
Princeton jug git_github
PDF
Speed up your Web applications with HTML5 WebSockets
PDF
Surviving as a Professional Software Developer
PDF
Becoming a professional software developer
Type script for_java_dev_jul_2020
Web sockets in Angular
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
TypeScript for Java Developers
Reactive Streams and RxJava2
Using JHipster 4 for generating Angular/Spring Boot apps
Angular 4 for Java Developers
Angular 2 for Java Developers
Overview of the AngularJS framework
RESTful services and OAUTH protocol in IoT
Intro to JavaScript
Java Intro: Unit1. Hello World
Running a Virtual Company
Princeton jug git_github
Speed up your Web applications with HTML5 WebSockets
Surviving as a Professional Software Developer
Becoming a professional software developer

Recently uploaded (20)

PDF
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
PDF
Build Multi-agent using Agent Development Kit
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
How to Confidently Manage Project Budgets
PPTX
ai tools demonstartion for schools and inter college
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
System and Network Administration Chapter 2
PPTX
CRUISE TICKETING SYSTEM | CRUISE RESERVATION SOFTWARE
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
Online Work Permit System for Fast Permit Processing
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
AI in Product Development-omnex systems
PPTX
Save Business Costs with CRM Software for Insurance Agents
PDF
Comprehensive Salesforce Implementation Services.pdf
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
Build Multi-agent using Agent Development Kit
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
How to Confidently Manage Project Budgets
ai tools demonstartion for schools and inter college
AIRLINE PRICE API | FLIGHT API COST |
Become an Agentblazer Champion Challenge Kickoff
How to Migrate SBCGlobal Email to Yahoo Easily
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
System and Network Administration Chapter 2
CRUISE TICKETING SYSTEM | CRUISE RESERVATION SOFTWARE
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
The Five Best AI Cover Tools in 2025.docx
Online Work Permit System for Fast Permit Processing
How Creative Agencies Leverage Project Management Software.pdf
AI in Product Development-omnex systems
Save Business Costs with CRM Software for Insurance Agents
Comprehensive Salesforce Implementation Services.pdf

Reactive Thinking in Java