SlideShare une entreprise Scribd logo
1  sur  53
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive ProgrammingAndres Almiray
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Toshiaki Maki
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and TomorrowVMware Tanzu
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
Intro to Reactive Programming
Intro to Reactive ProgrammingIntro to Reactive Programming
Intro to Reactive ProgrammingStéphane Maldini
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)Tracy Lee
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Roman Elizarov
 
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
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기흥배 최
 

Tendances (20)

Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and Tomorrow
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Intro to Reactive Programming
Intro to Reactive ProgrammingIntro to Reactive Programming
Intro to Reactive Programming
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Angular Lifecycle Hooks
Angular Lifecycle HooksAngular Lifecycle Hooks
Angular Lifecycle Hooks
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018
 
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
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Express js
Express jsExpress js
Express js
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
 

Similaire à RxJava - introduction & design

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
 
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
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Richard Langlois P. Eng.
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
Streamlining with rx
Streamlining with rxStreamlining with rx
Streamlining with rxAkhil Dad
 
Using redux and angular 2 with meteor
Using redux and angular 2 with meteorUsing redux and angular 2 with meteor
Using redux and angular 2 with meteorKen Ono
 
Using redux and angular 2 with meteor
Using redux and angular 2 with meteorUsing redux and angular 2 with meteor
Using redux and angular 2 with meteorKen Ono
 
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
 Akka-demy (a.k.a. How to build stateful distributed systems) I/II Akka-demy (a.k.a. How to build stateful distributed systems) I/II
Akka-demy (a.k.a. How to build stateful distributed systems) I/IIPeter Csala
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingAraf Karsh Hamid
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Legacy Typesafe (now Lightbend)
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingNick Hodge
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETJakub Malý
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 

Similaire à RxJava - introduction & design (20)

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
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and Reactor
 
Reactive Spring 5
Reactive Spring 5Reactive Spring 5
Reactive Spring 5
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5
 
Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Streamlining with rx
Streamlining with rxStreamlining with rx
Streamlining with rx
 
Using redux and angular 2 with meteor
Using redux and angular 2 with meteorUsing redux and angular 2 with meteor
Using redux and angular 2 with meteor
 
Using redux and angular 2 with meteor
Using redux and angular 2 with meteorUsing redux and angular 2 with meteor
Using redux and angular 2 with meteor
 
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
 Akka-demy (a.k.a. How to build stateful distributed systems) I/II Akka-demy (a.k.a. How to build stateful distributed systems) I/II
Akka-demy (a.k.a. How to build stateful distributed systems) I/II
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Taming Asynchrony using RxJS
Taming Asynchrony using RxJSTaming Asynchrony using RxJS
Taming Asynchrony using RxJS
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NET
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
Reactive mesh
Reactive meshReactive mesh
Reactive mesh
 

Plus de allegro.tech

Allegro Tech Talks Poznań #4: Jak przyspieszyć SOLRa w kilku prostych krokach.
Allegro Tech Talks Poznań #4: Jak przyspieszyć SOLRa w kilku prostych krokach. Allegro Tech Talks Poznań #4: Jak przyspieszyć SOLRa w kilku prostych krokach.
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 Data Science Meetup #2: Elasticsearch w praktyceallegro.tech Data Science Meetup #2: Elasticsearch w praktyce
allegro.tech Data Science Meetup #2: Elasticsearch w praktyceallegro.tech
 
[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegro
[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegro[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegro
[WHUG] Wielki brat patrzy - czyli jak zbieramy dane o użytkownikach allegroallegro.tech
 
Scaling infrastructure beyond containers
Scaling infrastructure beyond containersScaling infrastructure beyond containers
Scaling infrastructure beyond containersallegro.tech
 
Confitura 2015 - Code Quality Keepers @ Allegro
Confitura 2015 - Code Quality Keepers @ AllegroConfitura 2015 - Code Quality Keepers @ Allegro
Confitura 2015 - Code Quality Keepers @ Allegroallegro.tech
 
Confitura 2015 - Mikrousługi nie lubią być samotne
Confitura 2015 - Mikrousługi nie lubią być samotneConfitura 2015 - Mikrousługi nie lubią być samotne
Confitura 2015 - Mikrousługi nie lubią być samotneallegro.tech
 
RxJava & Hystrix - Perfect match for distributed applications
RxJava & Hystrix - Perfect match for distributed applicationsRxJava & Hystrix - Perfect match for distributed applications
RxJava & Hystrix - Perfect match for distributed applicationsallegro.tech
 
Microservices architecture pitfalls
Microservices architecture pitfallsMicroservices architecture pitfalls
Microservices architecture pitfallsallegro.tech
 
JDD 2014: Adam Dubiel - Import allegro.tech.internal.*
JDD 2014: Adam Dubiel - Import allegro.tech.internal.*JDD 2014: Adam Dubiel - Import allegro.tech.internal.*
JDD 2014: Adam Dubiel - Import allegro.tech.internal.*allegro.tech
 
Fighting with scale
Fighting with scaleFighting with scale
Fighting with scaleallegro.tech
 

Plus de allegro.tech (10)

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

Dernier

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Dernier (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

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