SlideShare a Scribd company logo
1
Mateusz Gajewski
Solutions Architect @ Allegro
Kraków Office Opening • February 2015
allegrotech.io, twitter: @allegrotechblog
RxJava
Reactive eXtensions for JVM
But first, let me introduce myself…
2
Talk agenda
• Problem statement
• Reactive programming concept
• Brief history of reactive extensions (RX)
• RxJava API contract
• Functional operators
• Schedulers
• Subjects
• Dealing with back-pressure
3
Problem
4
Statement: asynchronous programming is hard and error-prone
but still extremely indispensable
Possible approaches
• Future<T>,
• Guava’s ListenableFuture<T> (JVM6+)
• CompletableFuture<T> (JVM8)
• RxJava (JVM6+)
5
*Future(s) are not enough
• Supporting single (scalar) values,
• Future<T>.get(period, TimeUnit) still blocks
threads,
• Composing is hard - leading to callback hell,
• Complex flows required some kind of FSM,
• Error handling is error-prone :)
6
https://github.com/ReactiveX/RxJava
“RxJava – Reactive Extensions for the JVM – a
library for composing asynchronous and
event-based programs using observable
sequences for the Java VM”
7
Buzzword alert: reactive!
8
Reactive manifesto v2
Reactive system has to be:
9
Responsive thus react to users demand
Resilient thus react to errors and failure
Elastic thus react to load
Message-driven thus react to events and messages
Ok, but what’s reactive
programming in this context?
10
Reactive programming
• Wikipedia says: “Data flows and propagation of
change”,
• I prefer: “programming with asynchronous
(in)finite data sequences”
• Basically pushing data instead of pulling it
11
Reactive extensions
• Implement reactive programming paradigm over
(in)finite sequences of data,
• Push data propagation:
• Observer pattern on steroids,
• Declarative (functional) API for composing
sequences,
• Non-opinionated about source of concurrency
(schedulers, virtual time)
12
.NET was there first
and everybody is into it now
13
.NET was there first
• Version 1.0 released 17.11.2009,
• Shipped with .NET 4.0 by default,
• Version 2.0 released 15.08.2012,
• With a support for “Portable Library” (.NET 4.5)
• Reactive Extensions for JS released 17.03.2010
14
RxJava 1.0.x
• Ported from .NET to JVM by Netflix,
• Stable API release in November 2014,
• After nearly two years of development,
• Targeting Java (and Android), Scala, Groovy,
JRuby, Kotlin and Clojure,
• Last version 1.0.5 released 3 days ago
15
Observable<T> vs Iterable<T> vs
Future<T>
16
Scalar value Sequence
Synchronous T Iterable<T>
Asynchronous* Future<T> Observable<T>
* Observable is single-threaded by default
Observable is an ordered (serial) data sequence
17
* this is so called marble diagram (source: https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava)
RxJava API contract
18
Core types
• Observer<T>
• Observable<T>
• OnSubscribe<T>
• Producer
• Subscriber<T>
• Subscription
• Operator<T, R>
• Scheduler
• Subject<T>
19
Observer<T> contract
• methods:
• onNext(T)
• onError(Throwable T)
• onCompleted()
• onError/onCompleted called exactly once
20
Observer<T> example
21
Functional operators
22
Observable<T> functional API
23
Operator class Source type Result type
Anamorphic
aka unfold
T Observable<T>
Bind
aka map
Observable<T1> Observable<T2>
Catamorphic
aka fold or reduce
Observable<T> T
http://en.wikipedia.org/wiki/Anamorphism, http://en.wikipedia.org/wiki/Catamorphism
Unfold operatorsaka “how to create observables”
24
Operator Description
Observable.just(T value) Wraps plain value(s) into Observable
Observable.range(int from, int to) Generates range sequence
Observable.timer() Generates time-based sequence
Observable.interval() Generates interval-based sequence
Observable.create(OnSubscribe<T>) Creates observable with delegate (most powerful)
Observable.never() Empty sequence that never completes either way
Observable.empty() Empty sequence that completes right away
Observable.error(Throwable t) Empty sequence that completes with error
OnSubscribe<T>
25
OnSubscribe<T> contract
• onNext() called from a single thread (synchronisation is not
provided)
• onCompleted() and onError() called exactly once,
• Subscriber.isUnsubscribed() is checked prior to sending any
notification
• setProducer() is used to support reactive-pull back-pressure
26
Producer
• Provided to support reactive pull back-pressure,
• Observer can request n elements from producer,
• If n == Long.MAX_VALUE back-pressure is disabled,
• Still hard to use and do it right :(
• But there is some work being done with FSM to
better support back-pressure implementation
27
Producer example
28
Subscriber<T>
• Basically both Observer<T> and Subscription,
• Used in Operator<T, R> for lifting Observables
into Observables,
• Maintains subscription list
29
Operator<T, R>
• Covers “bind” operator class for lifting Observables
• Can preserve state in a scope of chained calls,
• Should maintain subscriptions and unsubscribe requests,
• It’s hard to write it right (composite subscriptions, back-
pressure, cascading unsubscribe requests)
30
Operator<T, R>
31
Transformer<T, R>
32
What will be the result? ;)
Operators categories
map and fold
33
Category Examples
Combining join, startWith, merge, concat, zip…
Conditional
amb, skipUntil, skipWhile, takeUntil, takeWhile,
defaultIfEmpty…
Filtering
filter, first, last, takeLast, skip, elementAt, sample, throttle,
timeout, distinct, distinctUntilChange, ofType,
ignoreElements…
Aggregating concat, count, reduce, collect, toList, toMap, toSortedList…
Transformational map, flatMap, switchMap, scan, groupBy, buffer, window…
See more: http://reactivex.io/documentation/operators.html
Schedulers
34
Schedulers
• Source of concurrency for Observables:
• Observable can use them via observeOn/subscribeOn,
• Schedules unit of work through Workers,
• Workers represent serial execution of work.
• Provides different processing strategies (Event Loop, Thread
Pools, etc),
• Couple provided out-of-the-box plus you can write your own
35
Schedulers
36
Name Description
Schedulers.computation()
Schedules computation bound work
(ScheduledExecutorService with pool size = NCPU, LRU
worker select strategy)
Schedulers.immediate() Schedules work on current thread
Schedulers.io()
I/O bound work (ScheduledExecutorService with growing
thread pool)
Schedulers.trampoline() Queues work on the current thread
Schedulers.newThread() Creates new thread for every unit of work
Schedulers.test() Schedules work on scheduler supporting virtual time
Schedulers.from(Executor e) Schedules work to be executed on provided executor
(subscribe|observe)On
• Think of them this way:
• subscribeOn - invocation of the subscription,
• observeOn - observing of the notifications
• Thus:
• subscribeOn for background processing and
warm-up
37
(subscribe|observe)On
38
What will be the result? ;)
Subjects
39
Subjects
• Subject is a proxy between Observable<T> and
Subscriber<T>
• It can subscribe multiple observables
• And emit items as an observable
• Different Subject types has different properties
40
AsyncSubject
BehaviourSubject
PublishSubject
ReplaySubject
Back-pressure
45
Cold vs hot observables
• Passive sequence is cold:
• Producing notifications when requested
• At rate Observer desires
• Ideal for reactive pull model of back-pressure using Producer.request(n)
• Active sequence is hot:
• Producing notifications regardless of subscriptions:
• Immediately when it is created
• At rate Observer sometimes cannot handle,
• Ideal for flow control strategies like buffering, windowing, throttling,
onBackpressure*
46
Cold vs hot examples
47
Cold Hot
Asynchronous requests
(Observable.from)
UI events (mouse clicks,
movements)
Created with OnSubscribe<T> Timer events
Subscriptions to queues Push pub/sub (broadcasts)
Dealing with back-pressure
48
https://github.com/ReactiveX/RxJava/wiki/Backpressure
onBackpressure*
49
Design considerations
• Reactive Extensions are not a silver-bullet for dealing with concurrency:
• Threading/synchronization concerns does not go away,
• You can still block your threads (dead-lock),
• Simple flows on top of RX and static sequences yields significant overhead,
• Choosing right operators flow is a challenge,
• You should avoid shared-state if possible (immutability FTW),
• Debugging is quite hard (but there is “plugins” mechanism),
• Understanding and using back-pressure well is harder :)
50
More reading
• Free Rx.NET books:
• Introduction to RX: http://www.introtorx.com/
• RX Design Guidelines: http://go.microsoft.com/fwlink/?LinkID=205219
• Reactive Extensions: http://reactivex.io
• Interactive RX diagrams: http://rxmarbles.com
• Reactive programming @ Netflix: http://techblog.netflix.com/2013/01/
reactive-programming-at-netflix.html
51
Interesting RX-enabled projects
• https://github.com/Netflix/Hystrix
• https://github.com/jersey/jersey
• https://github.com/square/retrofit
• https://github.com/ReactiveX/RxNetty
• https://github.com/couchbase/couchbase-java-client
• https://github.com/Netflix/ocelli
• https://github.com/davidmoten/rtree
52
Thank you
53

More Related Content

PDF
rx-java-presentation
Mateusz Bukowicz
 
PDF
Reactive programming with RxJava
Jobaer Chowdhury
 
PPTX
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
PDF
[오픈소스컨설팅]Java Performance Tuning
Ji-Woong Choi
 
PPTX
Presentation JEE et son écossystéme
Algeria JUG
 
PDF
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
ENSET, Université Hassan II Casablanca
 
PPT
Les Servlets et JSP
Korteby Farouk
 
PPTX
Diagramme de-composants152
Sirafina Rosa
 
rx-java-presentation
Mateusz Bukowicz
 
Reactive programming with RxJava
Jobaer Chowdhury
 
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
[오픈소스컨설팅]Java Performance Tuning
Ji-Woong Choi
 
Presentation JEE et son écossystéme
Algeria JUG
 
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
ENSET, Université Hassan II Casablanca
 
Les Servlets et JSP
Korteby Farouk
 
Diagramme de-composants152
Sirafina Rosa
 

What's hot (20)

ODP
Graylog
Diwakar Upadhyay
 
PPTX
Spring Boot and REST API
07.pallav
 
PDF
Stream All Things—Patterns of Modern Data Integration with Gwen Shapira
Databricks
 
PPTX
Javax.servlet,http packages
vamsi krishna
 
PPTX
Elastic - ELK, Logstash & Kibana
SpringPeople
 
PDF
Helm - Application deployment management for Kubernetes
Alexei Ledenev
 
PDF
Architecture jee principe de inversion de controle et injection des dependances
ENSET, Université Hassan II Casablanca
 
PDF
[오픈소스컨설팅]Tomcat6&7 How To
Ji-Woong Choi
 
PDF
[213]monitoringwithscouter 이건희
NAVER D2
 
PDF
eServices-Tp5: api management
Lilia Sfaxi
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PDF
Terraform introduction
Jason Vance
 
PPTX
Apache Kafka 0.8 basic training - Verisign
Michael Noll
 
PDF
Polymorphisme (cours, résumé)
Anis Bouhachem Djer
 
PDF
Site JEE de ECommerce Basé sur Spring IOC MVC Security JPA Hibernate
ENSET, Université Hassan II Casablanca
 
PDF
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
PDF
Symfony in microservice architecture
Daniele D'Angeli
 
PPTX
Introduction to helm
Jeeva Chelladhurai
 
PPTX
Intro to Helm for Kubernetes
Carlos E. Salazar
 
PDF
Exception handling
Anna Pietras
 
Spring Boot and REST API
07.pallav
 
Stream All Things—Patterns of Modern Data Integration with Gwen Shapira
Databricks
 
Javax.servlet,http packages
vamsi krishna
 
Elastic - ELK, Logstash & Kibana
SpringPeople
 
Helm - Application deployment management for Kubernetes
Alexei Ledenev
 
Architecture jee principe de inversion de controle et injection des dependances
ENSET, Université Hassan II Casablanca
 
[오픈소스컨설팅]Tomcat6&7 How To
Ji-Woong Choi
 
[213]monitoringwithscouter 이건희
NAVER D2
 
eServices-Tp5: api management
Lilia Sfaxi
 
Spring boot jpa
Hamid Ghorbani
 
Terraform introduction
Jason Vance
 
Apache Kafka 0.8 basic training - Verisign
Michael Noll
 
Polymorphisme (cours, résumé)
Anis Bouhachem Djer
 
Site JEE de ECommerce Basé sur Spring IOC MVC Security JPA Hibernate
ENSET, Université Hassan II Casablanca
 
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Symfony in microservice architecture
Daniele D'Angeli
 
Introduction to helm
Jeeva Chelladhurai
 
Intro to Helm for Kubernetes
Carlos E. Salazar
 
Exception handling
Anna Pietras
 
Ad

Similar to RxJava - introduction & design (20)

PDF
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
PDF
Springone2gx 2014 Reactive Streams and Reactor
Stéphane Maldini
 
PPTX
Reactive Spring 5
Corneil du Plessis
 
PDF
Reactive Programming in Java and Spring Framework 5
Richard Langlois P. Eng.
 
PPTX
Mini training - Reactive Extensions (Rx)
Betclic Everest Group Tech Team
 
PDF
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
PDF
Streamlining with rx
Akhil Dad
 
PDF
Using redux and angular 2 with meteor
Ken Ono
 
PDF
Using redux and angular 2 with meteor
Ken Ono
 
PPTX
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
Peter Csala
 
PPTX
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
PDF
Reactive Streams and RxJava2
Yakov Fain
 
PDF
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Legacy Typesafe (now Lightbend)
 
PDF
Project Reactor Now and Tomorrow
VMware Tanzu
 
PDF
RxJava@Android
Maxim Volgin
 
PPTX
Taming Asynchrony using RxJS
Angelo Simone Scotto
 
PDF
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
PPTX
Reactive programming
Nick Hodge
 
PPTX
Rx- Reactive Extensions for .NET
Jakub Malý
 
PDF
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
Springone2gx 2014 Reactive Streams and Reactor
Stéphane Maldini
 
Reactive Spring 5
Corneil du Plessis
 
Reactive Programming in Java and Spring Framework 5
Richard Langlois P. Eng.
 
Mini training - Reactive Extensions (Rx)
Betclic Everest Group Tech Team
 
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
Streamlining with rx
Akhil Dad
 
Using redux and angular 2 with meteor
Ken Ono
 
Using redux and angular 2 with meteor
Ken Ono
 
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
Peter Csala
 
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Reactive Streams and RxJava2
Yakov Fain
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Legacy Typesafe (now Lightbend)
 
Project Reactor Now and Tomorrow
VMware Tanzu
 
RxJava@Android
Maxim Volgin
 
Taming Asynchrony using RxJS
Angelo Simone Scotto
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu
 
Reactive programming
Nick Hodge
 
Rx- Reactive Extensions for .NET
Jakub Malý
 
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Ad

More from allegro.tech (10)

PDF
Allegro Tech Talks Poznań #4: Jak przyspieszyć SOLRa w kilku prostych krokach.
allegro.tech
 
PPTX
allegro.tech Data Science Meetup #2: Elasticsearch w praktyce
allegro.tech
 
PDF
[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegro
allegro.tech
 
PDF
Scaling infrastructure beyond containers
allegro.tech
 
PDF
Confitura 2015 - Code Quality Keepers @ Allegro
allegro.tech
 
PDF
Confitura 2015 - Mikrousługi nie lubią być samotne
allegro.tech
 
PDF
RxJava & Hystrix - Perfect match for distributed applications
allegro.tech
 
PDF
Microservices architecture pitfalls
allegro.tech
 
PDF
JDD 2014: Adam Dubiel - Import allegro.tech.internal.*
allegro.tech
 
PDF
Fighting with scale
allegro.tech
 
Allegro Tech Talks Poznań #4: Jak przyspieszyć SOLRa w kilku prostych krokach.
allegro.tech
 
allegro.tech Data Science Meetup #2: Elasticsearch w praktyce
allegro.tech
 
[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegro
allegro.tech
 
Scaling infrastructure beyond containers
allegro.tech
 
Confitura 2015 - Code Quality Keepers @ Allegro
allegro.tech
 
Confitura 2015 - Mikrousługi nie lubią być samotne
allegro.tech
 
RxJava & Hystrix - Perfect match for distributed applications
allegro.tech
 
Microservices architecture pitfalls
allegro.tech
 
JDD 2014: Adam Dubiel - Import allegro.tech.internal.*
allegro.tech
 
Fighting with scale
allegro.tech
 

Recently uploaded (20)

PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Doc9.....................................
SofiaCollazos
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Software Development Methodologies in 2025
KodekX
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 

RxJava - introduction & design

  • 1. 1 Mateusz Gajewski Solutions Architect @ Allegro Kraków Office Opening • February 2015 allegrotech.io, twitter: @allegrotechblog RxJava Reactive eXtensions for JVM
  • 2. But first, let me introduce myself… 2
  • 3. Talk agenda • Problem statement • Reactive programming concept • Brief history of reactive extensions (RX) • RxJava API contract • Functional operators • Schedulers • Subjects • Dealing with back-pressure 3
  • 4. Problem 4 Statement: asynchronous programming is hard and error-prone but still extremely indispensable
  • 5. Possible approaches • Future<T>, • Guava’s ListenableFuture<T> (JVM6+) • CompletableFuture<T> (JVM8) • RxJava (JVM6+) 5
  • 6. *Future(s) are not enough • Supporting single (scalar) values, • Future<T>.get(period, TimeUnit) still blocks threads, • Composing is hard - leading to callback hell, • Complex flows required some kind of FSM, • Error handling is error-prone :) 6
  • 7. https://github.com/ReactiveX/RxJava “RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM” 7
  • 9. Reactive manifesto v2 Reactive system has to be: 9 Responsive thus react to users demand Resilient thus react to errors and failure Elastic thus react to load Message-driven thus react to events and messages
  • 10. Ok, but what’s reactive programming in this context? 10
  • 11. Reactive programming • Wikipedia says: “Data flows and propagation of change”, • I prefer: “programming with asynchronous (in)finite data sequences” • Basically pushing data instead of pulling it 11
  • 12. Reactive extensions • Implement reactive programming paradigm over (in)finite sequences of data, • Push data propagation: • Observer pattern on steroids, • Declarative (functional) API for composing sequences, • Non-opinionated about source of concurrency (schedulers, virtual time) 12
  • 13. .NET was there first and everybody is into it now 13
  • 14. .NET was there first • Version 1.0 released 17.11.2009, • Shipped with .NET 4.0 by default, • Version 2.0 released 15.08.2012, • With a support for “Portable Library” (.NET 4.5) • Reactive Extensions for JS released 17.03.2010 14
  • 15. RxJava 1.0.x • Ported from .NET to JVM by Netflix, • Stable API release in November 2014, • After nearly two years of development, • Targeting Java (and Android), Scala, Groovy, JRuby, Kotlin and Clojure, • Last version 1.0.5 released 3 days ago 15
  • 16. Observable<T> vs Iterable<T> vs Future<T> 16 Scalar value Sequence Synchronous T Iterable<T> Asynchronous* Future<T> Observable<T> * Observable is single-threaded by default
  • 17. Observable is an ordered (serial) data sequence 17 * this is so called marble diagram (source: https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava)
  • 19. Core types • Observer<T> • Observable<T> • OnSubscribe<T> • Producer • Subscriber<T> • Subscription • Operator<T, R> • Scheduler • Subject<T> 19
  • 20. Observer<T> contract • methods: • onNext(T) • onError(Throwable T) • onCompleted() • onError/onCompleted called exactly once 20
  • 23. Observable<T> functional API 23 Operator class Source type Result type Anamorphic aka unfold T Observable<T> Bind aka map Observable<T1> Observable<T2> Catamorphic aka fold or reduce Observable<T> T http://en.wikipedia.org/wiki/Anamorphism, http://en.wikipedia.org/wiki/Catamorphism
  • 24. Unfold operatorsaka “how to create observables” 24 Operator Description Observable.just(T value) Wraps plain value(s) into Observable Observable.range(int from, int to) Generates range sequence Observable.timer() Generates time-based sequence Observable.interval() Generates interval-based sequence Observable.create(OnSubscribe<T>) Creates observable with delegate (most powerful) Observable.never() Empty sequence that never completes either way Observable.empty() Empty sequence that completes right away Observable.error(Throwable t) Empty sequence that completes with error
  • 26. OnSubscribe<T> contract • onNext() called from a single thread (synchronisation is not provided) • onCompleted() and onError() called exactly once, • Subscriber.isUnsubscribed() is checked prior to sending any notification • setProducer() is used to support reactive-pull back-pressure 26
  • 27. Producer • Provided to support reactive pull back-pressure, • Observer can request n elements from producer, • If n == Long.MAX_VALUE back-pressure is disabled, • Still hard to use and do it right :( • But there is some work being done with FSM to better support back-pressure implementation 27
  • 29. Subscriber<T> • Basically both Observer<T> and Subscription, • Used in Operator<T, R> for lifting Observables into Observables, • Maintains subscription list 29
  • 30. Operator<T, R> • Covers “bind” operator class for lifting Observables • Can preserve state in a scope of chained calls, • Should maintain subscriptions and unsubscribe requests, • It’s hard to write it right (composite subscriptions, back- pressure, cascading unsubscribe requests) 30
  • 32. Transformer<T, R> 32 What will be the result? ;)
  • 33. Operators categories map and fold 33 Category Examples Combining join, startWith, merge, concat, zip… Conditional amb, skipUntil, skipWhile, takeUntil, takeWhile, defaultIfEmpty… Filtering filter, first, last, takeLast, skip, elementAt, sample, throttle, timeout, distinct, distinctUntilChange, ofType, ignoreElements… Aggregating concat, count, reduce, collect, toList, toMap, toSortedList… Transformational map, flatMap, switchMap, scan, groupBy, buffer, window… See more: http://reactivex.io/documentation/operators.html
  • 35. Schedulers • Source of concurrency for Observables: • Observable can use them via observeOn/subscribeOn, • Schedules unit of work through Workers, • Workers represent serial execution of work. • Provides different processing strategies (Event Loop, Thread Pools, etc), • Couple provided out-of-the-box plus you can write your own 35
  • 36. Schedulers 36 Name Description Schedulers.computation() Schedules computation bound work (ScheduledExecutorService with pool size = NCPU, LRU worker select strategy) Schedulers.immediate() Schedules work on current thread Schedulers.io() I/O bound work (ScheduledExecutorService with growing thread pool) Schedulers.trampoline() Queues work on the current thread Schedulers.newThread() Creates new thread for every unit of work Schedulers.test() Schedules work on scheduler supporting virtual time Schedulers.from(Executor e) Schedules work to be executed on provided executor
  • 37. (subscribe|observe)On • Think of them this way: • subscribeOn - invocation of the subscription, • observeOn - observing of the notifications • Thus: • subscribeOn for background processing and warm-up 37
  • 40. Subjects • Subject is a proxy between Observable<T> and Subscriber<T> • It can subscribe multiple observables • And emit items as an observable • Different Subject types has different properties 40
  • 46. Cold vs hot observables • Passive sequence is cold: • Producing notifications when requested • At rate Observer desires • Ideal for reactive pull model of back-pressure using Producer.request(n) • Active sequence is hot: • Producing notifications regardless of subscriptions: • Immediately when it is created • At rate Observer sometimes cannot handle, • Ideal for flow control strategies like buffering, windowing, throttling, onBackpressure* 46
  • 47. Cold vs hot examples 47 Cold Hot Asynchronous requests (Observable.from) UI events (mouse clicks, movements) Created with OnSubscribe<T> Timer events Subscriptions to queues Push pub/sub (broadcasts)
  • 50. Design considerations • Reactive Extensions are not a silver-bullet for dealing with concurrency: • Threading/synchronization concerns does not go away, • You can still block your threads (dead-lock), • Simple flows on top of RX and static sequences yields significant overhead, • Choosing right operators flow is a challenge, • You should avoid shared-state if possible (immutability FTW), • Debugging is quite hard (but there is “plugins” mechanism), • Understanding and using back-pressure well is harder :) 50
  • 51. More reading • Free Rx.NET books: • Introduction to RX: http://www.introtorx.com/ • RX Design Guidelines: http://go.microsoft.com/fwlink/?LinkID=205219 • Reactive Extensions: http://reactivex.io • Interactive RX diagrams: http://rxmarbles.com • Reactive programming @ Netflix: http://techblog.netflix.com/2013/01/ reactive-programming-at-netflix.html 51
  • 52. Interesting RX-enabled projects • https://github.com/Netflix/Hystrix • https://github.com/jersey/jersey • https://github.com/square/retrofit • https://github.com/ReactiveX/RxNetty • https://github.com/couchbase/couchbase-java-client • https://github.com/Netflix/ocelli • https://github.com/davidmoten/rtree 52