SlideShare una empresa de Scribd logo
1 de 32
TOMASZ KOWALCZEWSKI
REACTIVE JAVA
RX JAVA BY NETFLIX
 Open source project with Apache License.
 Java implementation of Rx Observables from Microsoft
 The Netflix API uses it to make the entire service layer asynchronous
 Provides a DSL for creating computation flows out of asynchronous sources
using collection of operators for filtering, selecting, transforming and
combining that flows in a lazy manner
 These flows are called Observables – collection of events with push
semantics (as oposed to pull in Iterator)
 Targets the JVM not a language. Currently supports Java, Groovy, Clojure,
and Scala
OBSERVABLE ->
OBSERVABLE ->
OBSERVER ->
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
boolean alive();
}
public interface ShrödingersCat {
Future<Boolean> alive();
}
public interface ShrödingersCat {
Iterator<Boolean> alive();
}
REACTIVE
“readily responsive to a stimulus”
Merriam-Webster dictionary
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
Observable<Boolean> alive();
}
SUBCRIPTIONS AND EVENTS
t
subscribe
onNext*
onCompleted | onError
SERVICE RETURNING OBSERVABLE
public interface ShrödingersCat {
Observable<Boolean> alive();
}
cat
.alive()
.subscribe(status -> System.out.println(status));
public interface ShrödingersCat {
Observable<Boolean> alive();
}
cat
.alive()
.throttleWithTimeout(250, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
.filter(isAlive -> isAlive)
.map(Boolean::toString)
.subscribe(status -> display.display(status));
SERVICE RETURNING OBSERVABLE
 Maybe it executes its logic on subscriber thread?
 Maybe it delegates part of the work to other threads?
 Does it use NIO?
 Maybe its an actor?
 Does it return cached data?
 Observer does not care!
HOW IS THE OBSERVABLE IMPLEMENTED?
MARBLE DIAGRAMS
MAP(FUNC1)
MERGE(OBSERVABLE...)
CONCAT(OBSERVABLE...)
FLATMAP(FUNC)
Observable<ShrödingersCat> cats = listAllCats();
cats
.flatMap(cat ->
Observable
.from(catService.getPicturesFor(cat))
.filter(image -> image.size() < 100 * 1000)
)
).subscribe();
FLATMAP(FUNC)
CACHE
Random random = new Random();
Observable<Integer> observable = Observable
.range(1, 100)
.map(random::nextInt)
.cache();
observable.subscribe(System.out::println);
observable.subscribe(System.out::println);
...
 Always prints same values
DEBOUNCE(LONG TIMEOUT, TIMEUNIT TU)
INJECTING CUSTOM OPERATORS USING LIFT
class InternStrings implements Observable.Operator<String, String> {
public Subscriber<String> call(Subscriber<String> subscriber) {
return new Subscriber<String>() {
public void onCompleted() { subscriber.onCompleted(); }
public void onError(Throwable e) { subscriber.onError(e); }
public void onNext(String s) {
subscriber.onNext(s.intern());
}
};
}
}
Observable
.from("AB", "CD", "AB", "DE")
.lift(new InternStrings())
.subscribe();
ERROR HANDLING
 Correctly implemented observable will not produce any events after
error notification
 Operators available for fixing observables not adhering to this rule
 Pass custom error handling function to subscribe
 Transparently substite failing observable with another one
 Convert error into regular event
 Retry subscription in hope this time it will work...
ESCAPING THE MONAD
Iterable<String> strings = Observable.from(1, 2, 3, 4)
.map(i -> Integer.toString(i))
.toBlockingObservable()
.toIterable();
// or (and many more)
T firstOrDefault(T defaultValue, Func1 predicate)
Iterator<T> getIterator()
Iterable<T> next()
 Inverses the dependency, will wait for next item, then execute
 Usually to interact with other, synchronous APIs
 While migrating to reactive approach in small increments
 To trigger early evaluation while debugging
OBSERVER
public interface Observer<T> {
void onCompleted();
void onError(Throwable e);
void onNext(T args);
}
CREATING OBSERVABLES
Observable<Boolean> watchTheCat =
Observable.create(observer -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
});
 create accepts OnSubscribe function
 Executed for every subscriber upon subscription
 This example is not asynchronous
CREATING OBSERVABLES
Observable.create(observer -> {
Future<?> brighterFuture = executorService.submit(() -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
});
subscriber.add(Subscriptions.from(brighterFuture));
});
 Executes code in separate thread (from thread pool executorService)
 Stream of events is delivered by the executor thread
 Thread calling onNext() runs all the operations defined on observable
 Future is cancelled if client unsubscribes
CREATING OBSERVABLES
Observable<Boolean> watchTheCat =
Observable.create(observer -> {
observer.onNext(cat.isAlive());
observer.onCompleted();
})
.subscribeOn(scheduler);
 Subscribe function is executed on supplied scheduler (thin wrapper
over java.util.concurrent.Executor)
SUBSCRIPTION
public interface Subscription {
void unsubscribe();
boolean isUnsubscribed();
}
UNSUBSCRIBING
Observable.create(subscriber -> {
for (long i = 0; !subscriber.isUnsubscribed(); i++) {
subscriber.onNext(i);
System.out.println("Emitted: " + i);
}
subscriber.onCompleted();
})
.take(10)
.subscribe(aLong -> {
System.out.println("Got: " + aLong);
});
 Take operator unsubscribes from observable after 10 iterations
CONCURRENCY
 Synchronous vs. asynchonous, single or multiple threaded is
implementation detail of service provider (Observable)
 As long as onNext calls are not executed concurrently
 So the framework does not have to synchronize everything
 Operators combining many Observables ensure serialized access
 In face of misbehaving observable serialize() operator forces
correct behaviour
 Passing pure functions to Rx operators is always the best bet
LESSONS LEARNED
 In our use cases performance profile is dominated by other system
components
 Performance depends on implementation of used operators and
may vary
 Contention points on operators that merge streams
 Some operators require scheduler, default is NewThreadScheduler
 Creating 1000s of threads and reaching `ulimit –u` - system
almost freezes :)
 Debugging and reasoning about subscriptions is not always easy.
 Insert doOnEach or doOnNext calls for debugging
 IDE support not satisfactory, problems in placing breakpoints inside
closures – IntelliJ IDEA 13 has smart step into closures which my
help
MORE INFORMATION
 https://github.com/Netflix/RxJava
 https://github.com/Netflix/RxJava/wiki
 http://www.infoq.com/author/Erik-Meijer
 React conference
http://www.youtube.com/playlist?list=PLSD48HvrE7-
Z1stQ1vIIBumB0wK0s8llY
 Cat picture taken from http://www.teckler.com/en/Rapunzel

Más contenido relacionado

La actualidad más candente

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
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaFabio Collini
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015Constantine Mars
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 

La actualidad más candente (20)

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
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 

Destacado

Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)GlobalLogic Ukraine
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Jean-Paul Calbimonte
 
RDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsRDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsJean-Paul Calbimonte
 
Colombia career market 01.27.2015
Colombia career market 01.27.2015Colombia career market 01.27.2015
Colombia career market 01.27.2015Felipe Saenz M
 
Final - advertising
Final - advertisingFinal - advertising
Final - advertisingasofaihp
 
Something from nothing
Something from nothingSomething from nothing
Something from nothingmsourgiad
 
Get your facebook out of my twitter
Get your facebook out of my twitterGet your facebook out of my twitter
Get your facebook out of my twitterprofessormedic
 
Co to jest iPresso?
Co to jest iPresso?Co to jest iPresso?
Co to jest iPresso?iPresso
 
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideA Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideP9P
 
Social studies chap 1 subject 1
Social studies chap 1  subject 1Social studies chap 1  subject 1
Social studies chap 1 subject 1Gladimar Marín
 
Badminton by Molly Naylor
Badminton by Molly NaylorBadminton by Molly Naylor
Badminton by Molly NaylorBurning Eye
 
Peperiksaan ptd 2012
Peperiksaan ptd 2012Peperiksaan ptd 2012
Peperiksaan ptd 2012exam_ptd_2012
 

Destacado (20)

Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015
 
RDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsRDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementations
 
Ldap howto
Ldap howtoLdap howto
Ldap howto
 
Webcasting
WebcastingWebcasting
Webcasting
 
Ptd m41 2012
Ptd m41 2012Ptd m41 2012
Ptd m41 2012
 
Colombia career market 01.27.2015
Colombia career market 01.27.2015Colombia career market 01.27.2015
Colombia career market 01.27.2015
 
Final - advertising
Final - advertisingFinal - advertising
Final - advertising
 
Something from nothing
Something from nothingSomething from nothing
Something from nothing
 
Question 4
Question 4Question 4
Question 4
 
Making waves
Making wavesMaking waves
Making waves
 
Get your facebook out of my twitter
Get your facebook out of my twitterGet your facebook out of my twitter
Get your facebook out of my twitter
 
Mobile money 2015
Mobile money 2015Mobile money 2015
Mobile money 2015
 
Co to jest iPresso?
Co to jest iPresso?Co to jest iPresso?
Co to jest iPresso?
 
Q3
Q3Q3
Q3
 
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s GuideA Five-Session Adult Christian Education Curriculum - Leader’s Guide
A Five-Session Adult Christian Education Curriculum - Leader’s Guide
 
Social studies chap 1 subject 1
Social studies chap 1  subject 1Social studies chap 1  subject 1
Social studies chap 1 subject 1
 
Badminton by Molly Naylor
Badminton by Molly NaylorBadminton by Molly Naylor
Badminton by Molly Naylor
 
Peperiksaan ptd 2012
Peperiksaan ptd 2012Peperiksaan ptd 2012
Peperiksaan ptd 2012
 

Similar a Reactive Java (GeeCON 2014)

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftAaron Douglas
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiNexus FrontierTech
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixTracy Lee
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUIkiahiska
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaMatt Stine
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 

Similar a Reactive Java (GeeCON 2014) (20)

Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 

Más de Tomasz Kowalczewski

Más de Tomasz Kowalczewski (12)

How I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfHow I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdf
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)
 
Everybody Lies
Everybody LiesEverybody Lies
Everybody Lies
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Measure to fail
Measure to failMeasure to fail
Measure to fail
 
Reactive Java at JDD 2014
Reactive Java at JDD 2014Reactive Java at JDD 2014
Reactive Java at JDD 2014
 
Java 8 jest tuż za rogiem
Java 8 jest tuż za rogiemJava 8 jest tuż za rogiem
Java 8 jest tuż za rogiem
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 

Último

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Último (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

Reactive Java (GeeCON 2014)

  • 2. RX JAVA BY NETFLIX  Open source project with Apache License.  Java implementation of Rx Observables from Microsoft  The Netflix API uses it to make the entire service layer asynchronous  Provides a DSL for creating computation flows out of asynchronous sources using collection of operators for filtering, selecting, transforming and combining that flows in a lazy manner  These flows are called Observables – collection of events with push semantics (as oposed to pull in Iterator)  Targets the JVM not a language. Currently supports Java, Groovy, Clojure, and Scala
  • 3.
  • 6. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { boolean alive(); } public interface ShrödingersCat { Future<Boolean> alive(); } public interface ShrödingersCat { Iterator<Boolean> alive(); }
  • 7. REACTIVE “readily responsive to a stimulus” Merriam-Webster dictionary
  • 8. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); }
  • 10. SERVICE RETURNING OBSERVABLE public interface ShrödingersCat { Observable<Boolean> alive(); } cat .alive() .subscribe(status -> System.out.println(status));
  • 11. public interface ShrödingersCat { Observable<Boolean> alive(); } cat .alive() .throttleWithTimeout(250, TimeUnit.MILLISECONDS) .distinctUntilChanged() .filter(isAlive -> isAlive) .map(Boolean::toString) .subscribe(status -> display.display(status)); SERVICE RETURNING OBSERVABLE
  • 12.  Maybe it executes its logic on subscriber thread?  Maybe it delegates part of the work to other threads?  Does it use NIO?  Maybe its an actor?  Does it return cached data?  Observer does not care! HOW IS THE OBSERVABLE IMPLEMENTED?
  • 18. Observable<ShrödingersCat> cats = listAllCats(); cats .flatMap(cat -> Observable .from(catService.getPicturesFor(cat)) .filter(image -> image.size() < 100 * 1000) ) ).subscribe(); FLATMAP(FUNC)
  • 19. CACHE Random random = new Random(); Observable<Integer> observable = Observable .range(1, 100) .map(random::nextInt) .cache(); observable.subscribe(System.out::println); observable.subscribe(System.out::println); ...  Always prints same values
  • 21. INJECTING CUSTOM OPERATORS USING LIFT class InternStrings implements Observable.Operator<String, String> { public Subscriber<String> call(Subscriber<String> subscriber) { return new Subscriber<String>() { public void onCompleted() { subscriber.onCompleted(); } public void onError(Throwable e) { subscriber.onError(e); } public void onNext(String s) { subscriber.onNext(s.intern()); } }; } } Observable .from("AB", "CD", "AB", "DE") .lift(new InternStrings()) .subscribe();
  • 22. ERROR HANDLING  Correctly implemented observable will not produce any events after error notification  Operators available for fixing observables not adhering to this rule  Pass custom error handling function to subscribe  Transparently substite failing observable with another one  Convert error into regular event  Retry subscription in hope this time it will work...
  • 23. ESCAPING THE MONAD Iterable<String> strings = Observable.from(1, 2, 3, 4) .map(i -> Integer.toString(i)) .toBlockingObservable() .toIterable(); // or (and many more) T firstOrDefault(T defaultValue, Func1 predicate) Iterator<T> getIterator() Iterable<T> next()  Inverses the dependency, will wait for next item, then execute  Usually to interact with other, synchronous APIs  While migrating to reactive approach in small increments  To trigger early evaluation while debugging
  • 24. OBSERVER public interface Observer<T> { void onCompleted(); void onError(Throwable e); void onNext(T args); }
  • 25. CREATING OBSERVABLES Observable<Boolean> watchTheCat = Observable.create(observer -> { observer.onNext(cat.isAlive()); observer.onCompleted(); });  create accepts OnSubscribe function  Executed for every subscriber upon subscription  This example is not asynchronous
  • 26. CREATING OBSERVABLES Observable.create(observer -> { Future<?> brighterFuture = executorService.submit(() -> { observer.onNext(cat.isAlive()); observer.onCompleted(); }); subscriber.add(Subscriptions.from(brighterFuture)); });  Executes code in separate thread (from thread pool executorService)  Stream of events is delivered by the executor thread  Thread calling onNext() runs all the operations defined on observable  Future is cancelled if client unsubscribes
  • 27. CREATING OBSERVABLES Observable<Boolean> watchTheCat = Observable.create(observer -> { observer.onNext(cat.isAlive()); observer.onCompleted(); }) .subscribeOn(scheduler);  Subscribe function is executed on supplied scheduler (thin wrapper over java.util.concurrent.Executor)
  • 28. SUBSCRIPTION public interface Subscription { void unsubscribe(); boolean isUnsubscribed(); }
  • 29. UNSUBSCRIBING Observable.create(subscriber -> { for (long i = 0; !subscriber.isUnsubscribed(); i++) { subscriber.onNext(i); System.out.println("Emitted: " + i); } subscriber.onCompleted(); }) .take(10) .subscribe(aLong -> { System.out.println("Got: " + aLong); });  Take operator unsubscribes from observable after 10 iterations
  • 30. CONCURRENCY  Synchronous vs. asynchonous, single or multiple threaded is implementation detail of service provider (Observable)  As long as onNext calls are not executed concurrently  So the framework does not have to synchronize everything  Operators combining many Observables ensure serialized access  In face of misbehaving observable serialize() operator forces correct behaviour  Passing pure functions to Rx operators is always the best bet
  • 31. LESSONS LEARNED  In our use cases performance profile is dominated by other system components  Performance depends on implementation of used operators and may vary  Contention points on operators that merge streams  Some operators require scheduler, default is NewThreadScheduler  Creating 1000s of threads and reaching `ulimit –u` - system almost freezes :)  Debugging and reasoning about subscriptions is not always easy.  Insert doOnEach or doOnNext calls for debugging  IDE support not satisfactory, problems in placing breakpoints inside closures – IntelliJ IDEA 13 has smart step into closures which my help
  • 32. MORE INFORMATION  https://github.com/Netflix/RxJava  https://github.com/Netflix/RxJava/wiki  http://www.infoq.com/author/Erik-Meijer  React conference http://www.youtube.com/playlist?list=PLSD48HvrE7- Z1stQ1vIIBumB0wK0s8llY  Cat picture taken from http://www.teckler.com/en/Rapunzel