SlideShare a Scribd company logo
1 of 77
Download to read offline
Reactive Programming with
RxJava
Jobaer Chowdhury
Technical Project Manager, Cefalo
Presented @ JUGBD 6.0 (25/02/2017)
Writing concurrent code in Java is hard.
Writing correct concurrent code is even
harder
Unless you’ve read
this from cover to
cover, twice :-)
What is RxJava?
What is RxJava?
- A library for composing asynchronous and event based programs
We can write concurrent code using RxJava library without worrying about low
level threads, locks and synchronization.
Brief history or Rx
Reactive Extensions: first introduced by Microsoft
RxJava: the jvm implementation was first developed by Netflix
Current version is 2.x
(I’ll talk about version 1.x here)
RxJava: Most starred java repository on
Github
Many implementations
Rx.NET
RxJava
RxJS
RxScala
RxClojure
…. And some others
So let’s get started ...
Observable<T> is the heart of RxJava
Observable<T>
… a flowing sequence of values
… a stream of events
An observer can subscribe to the Observable
The Observable may call onNext(), onError() or onCompleted() on
the observer
Let’s compare Observables to Iterables
We all know Iterables, right?
Iterable<T> {
Iterator<T> iterator();
}
Iterator<T> {
Boolean hasNext();
T next();
}
Observable duality with Iterable
Iterable<T>, Iterator<T>
● Get an iterator
● hasNext(), next()
● Pull based
● Sync
Observable<T>, Observer<T>
● Subscribe an observer
● onNext(), onError(), onCompleted()
● Push based
● Async
Observable<T> examples
● Observable<Tweet>
● Observable<Temperature>
● Observable<Person>
● Observable<HttpResponse>
● Observable<MouseEvent>
….. and so on
Hello Observable!
Let’s create an Observable<String> that will emit “Hello, world!”
Observable<String> hello = Observable.create(obs -> {
obs.onNext(“Hello, world!”);
});
And we can subscribe to it ...
Observable<String> hello = Observable.create(obs -> {
obs.onNext(“Hello, world!”);
});
hello.subscribe(s -> {
System.out.println(s);
});
We can simplify the creation here
Observable<String> hello = Observable.just(“Hello, World!”);
We can also handle errors and completed event
Observable<String> hello = Observable.just(“Hello, World!”);
hello.subscribe(
val -> {System.out.println(val);},
error -> {System.out.println(“Error occurred”);},
() -> { System.out.println(“Completed”)};
})
We’ve seen how we can create
Observables, and how to consume them.
Let’s see how we can modify/operate on
Observables
Observable.filter example
Observable<Integer> numbers = Observable.just(1, 2, 3, 4, 5, 6);
Observable<Integer> result = numbers.filter(num -> num % 2 == 0);
// the result will contain 2, 4, 6 inside the Observables
Observable.map example
// We have a function that gives us an Observable of ints
Observable<Integer> ids = searchForArticles(“dhaka”);
// another function that takes an int, and returns an article
Article loadArticle(Integer articleId) {...}
Observable<Article> result = ids.map(id -> loadArticle(id));
Observable.flatMap example
// We have a function that gives us an Observable of ints
Observable<Integer> ids = searchForArticles(“dhaka”);
// and a function returns an article wrapped inside Observable
Observable<Article> loadArticle(Integer articleId) {...}
Observable<Article> result = ids.flatMap(id -> loadArticle(id));
Map vs. flatMap
Map vs. flatMap example
Observable<Integer> ids = searchForArticles(“dhaka”);
Observable<Article> loadArticle(Integer articleId) {...}
Observable<Observable<Article>> res = ids.map(this::loadArticle);
Observable<Article> result = ids.flatMap(this::loadArticle);
There are many more operators ...
Let’s use Observables to solve a real
world problem
A real world example
Let’s assume we are working for a news service. And we have the following
requirements.
● Do a search for a term on the search server. The search server will return
some ids
● For each id load the news article from db.
● For each id find out how many likes the article has on social network
● Merge the result from above two steps and send it to view layer
Let’s assume we have the following (sync) API
List<Integer> searchForArticles(String query)
PersistentArticle loadArticle(Integer articleId)
Integer fetchLikeCount(Integer articleId)
…. and we can create article by using the db object and like count
Article result = new Article(PersistentArticle, Integer)
One way of solving it
List<Integer> searchResult = searchForArticles(“dhaka”);
List<Article> result = new ArrayList<>();
for(Integer id : searchResult) {
PersistentArticle pa = loadArticle(id)
Integer likes = fetchLikeCount(id)
result.add(new Article(pa, likes));
}
return result;
Do you see any problem with this code?
It’s sequential, and may take some time
to run.
When an article is loading, nothing
prevents us from fetching the like count
of that article,
or loading another article, right?
A concurrent solution may save us
running time. And we can use
Observables to do so.
Let’s try to use Observables now
Let’s assume now we have an async API
Observable<Integer> searchForArticles(String query)
Observable<PersistentArticle> loadArticle(Integer articleId)
Observable<Integer> fetchLikeCount(Integer articleId)
And we need to come up with the result as the following type.
Observable<Article> result = … ;
// We can use the result like following
result.subscribe(article -> {//update the view with it});
Don’t worry about how the async API
was implemented. Just assume it is
present.
(If we only have a sync api, we can still make it async by wrapping things inside
Observables, using Observable.create, just etc.)
First step: do the search
Observable<Integer> ids = searchForArticles(String query);
….
For each id we need to load the article and fetch the like count.
How do we get the ids out from the
Observable?
We don’t, instead we apply some
operator to transform the source
Observable to a different one
Let’s go back to few slides ago, and see
how we solved the problem sequentially
The traditional solution ...
List<Integer> searchResult = searchForArticles(“dhaka”);
List<Article> result = new ArrayList<>();
for(Integer id : searchResult) {
PersistentArticle pa = loadArticle(id)
Integer likes = fetchLikeCount(id)
result.add(new Article(pa, likes));
}
return result;
But we don’t do it like this in rx
Many Observable operators take lambda
as parameter.
And we can get the item from inside the
Observable box as a parameter of our
supplied lambda.
In case of Observable.filter
Observable<Integer> numbers = Observable.just(1, 2, 3, 4, 5, 6);
numbers.filter(num -> num % 2 == 0);
// The Observable.filter operator takes a lambda as parameter
// We pass it a lambda
// Our supplied lambda will be called for each of the item
// So here the parameter “num” will represent an item inside the box
// This is how we get things out from Observable box.
So, let’s get back to the original question
Observable<Integer> ids = searchForArticles(String query);
….
For each id we need to load the article and fetch the like count.
Now we know we need to apply some
operator, which one?
We have to apply flatMap
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
// do something with the id
...
});
So, by applying flatMap, we somehow get the item from inside the Observable
box, as the parameter of our lambda.
We have to apply flatMap
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
Observable<PersistentArticle> arts = loadArticle(id);
Observable<Integer> likes = fetchLikeCount(id);
//how do we get the article out from inside Observable?
});
We need to apply flatMap again ...
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
Observable<PersistentArticle> arts = loadArticle(id);
Observable<Integer> likes = fetchLikeCount(id);
return arts.flatMap(art -> {
// and now we need to get the likes out
});
})
And flatMap again ...
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
Observable<PersistentArticle> arts = loadArticle(id);
Observable<Integer> likes = fetchLikeCount(id);
return arts.flatMap(art -> {
return likes.flatMap(like -> {
// now we have everything to make an Article object
// so what do we return here? A new Article()?
});
});
})
We need to wrap the result inside Observable
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
Observable<PersistentArticle> arts = loadArticle(id);
Observable<Integer> likes = fetchLikeCount(id);
return arts.flatMap(art -> {
return likes.flatMap(like -> {
return Observable.just(new Article(art, like));
});
});
})
We can remove some nesting here ...
Alternate version using zip
Observable<Integer> ids = searchForArticles(query);
ids.flatMap(id -> {
Observable<PersistentArticle> arts = loadArticle(id);
Observable<Integer> likes = fetchLikeCount(id);
return Observable.zip(arts, likes, (art, lc) -> {
return new Article(art, lc);
});
});
})
Using the full power of Java 8 …
searchForArticles(query).flatMap(id -> {
return zip(loadArticle(id),
fetchLikeCount(id),
Article::new);
});
});
Using the full power of Java 8 …
searchForArticles(query).flatMap(id -> {
return zip(loadArticle(id),
fetchLikeCount(id),
Article::new);
});
});
This is the solution we desire. I find this code beautiful. And it’s (mostly)
concurrent (depending on the implementation of the search, load, etc.).
Keep these in mind while using RxJava
● Observables can emit zero, one or more items
● Observables can be of infinite stream of values/events
● Observables can complete without returning anything, Observable.empty().
● Observables can emit some items and then call onError() to terminate
abnormally
● If onError() is called, then onCompleted will not be called
Keep these in mind while using RxJava
● Observables are by default lazy. If no subscriber is subscribed, then nothing
will be executed.
● By default they run in the same thread from which the subscriber is called
● You can change the subscriber thread by calling subscribeOn()
● You can change the observer thread by calling observeOn()
● There are some built in Schedulers (similar to thread pool). For example
Schedulers.io(), Schedulers.computation().
● A single Observable issues notifications to observers serially (not in parallel).
A better version of the previous code
searchForArticles(query).flatMap(id -> {
return Observable.just(id)
.subscribeOn(Schedulers.io())
.flatMap(i ->{
return zip(loadArticle(i),
fetchLikeCount(i),
Article::new);
});
});
});
In fact this is the concurrent version, although it lost it’s beauty a bit :-)
Hoping to cover this in a future session.
When you have multiple async or
concurrent things, depending on each
other, RxJava may be a good candidate.
I only covered the basics, there are way
more to learn …
Advanced topics (maybe in some future sessions)
A whole lot more operators
Subjects
Schedulers
Backpressure
Implementing custom operators
Have a look into
● CompletableFuture (introduced in java 8)
● Reactive streams specification (which RxJava 2.x implemented)
● java.util.concurrent.Flow api (coming in java 9)
Reference
● Collection of all tutorials, http://reactivex.io/tutorials.html
● Reactive programming with RxJava book,
http://shop.oreilly.com/product/0636920042228.do
● The RxJava contract, http://reactivex.io/documentation/contract.html
Thank you!

More Related Content

What's hot

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
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default MethodsHaim Michael
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Philip Schwarz
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Ippon
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New FeaturesHaim Michael
 
Introduction to Spring webflux
Introduction to Spring webfluxIntroduction to Spring webflux
Introduction to Spring webfluxKnoldus Inc.
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé Paumard
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안SANG WON PARK
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 

What's hot (20)

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
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
 
Java spring batch
Java spring batchJava spring batch
Java spring batch
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Redux Thunk
Redux ThunkRedux Thunk
Redux Thunk
 
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014Formation JPA Avancé / Hibernate gratuite par Ippon 2014
Formation JPA Avancé / Hibernate gratuite par Ippon 2014
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
 
Introduction to Spring webflux
Introduction to Spring webfluxIntroduction to Spring webflux
Introduction to Spring webflux
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Php operators
Php operatorsPhp operators
Php operators
 
Spring Webflux
Spring WebfluxSpring Webflux
Spring Webflux
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Viewers also liked

Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJosé Paumard
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 
Modern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.xModern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.xThomas Segismont
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixFlorina Muntenescu
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 
Real-world applications of the Reactive Extensions
Real-world applications of the Reactive ExtensionsReal-world applications of the Reactive Extensions
Real-world applications of the Reactive ExtensionsJonas Chapuis
 
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
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
A Journey Through MV Wonderland
A Journey Through MV WonderlandA Journey Through MV Wonderland
A Journey Through MV WonderlandFlorina Muntenescu
 
Android DevConference - Dagger 2: uso avançado em projetos Android
Android DevConference - Dagger 2: uso avançado em projetos AndroidAndroid DevConference - Dagger 2: uso avançado em projetos Android
Android DevConference - Dagger 2: uso avançado em projetos AndroidiMasters
 
Retro vs Volley
Retro vs VolleyRetro vs Volley
Retro vs VolleyArtjoker
 
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
 
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민 track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민 양 한빛
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 

Viewers also liked (20)

Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Jugbd meet up 6
Jugbd meet up 6Jugbd meet up 6
Jugbd meet up 6
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Modern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.xModern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.x
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mix
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 
Real-world applications of the Reactive Extensions
Real-world applications of the Reactive ExtensionsReal-world applications of the Reactive Extensions
Real-world applications of the Reactive Extensions
 
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
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Code Learn Share
Code Learn ShareCode Learn Share
Code Learn Share
 
A Journey Through MV Wonderland
A Journey Through MV WonderlandA Journey Through MV Wonderland
A Journey Through MV Wonderland
 
Android DevConference - Dagger 2: uso avançado em projetos Android
Android DevConference - Dagger 2: uso avançado em projetos AndroidAndroid DevConference - Dagger 2: uso avançado em projetos Android
Android DevConference - Dagger 2: uso avançado em projetos Android
 
Retro vs Volley
Retro vs VolleyRetro vs Volley
Retro vs Volley
 
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
 
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민 track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민
track2 04. MS는 Rx를 왜 만들었을까? feat. RxJS/ 네이버, 김훈민
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 

Similar to Reactive programming with RxJava

Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Alpine academy apache spark series #1 introduction to cluster computing wit...
Alpine academy apache spark series #1   introduction to cluster computing wit...Alpine academy apache spark series #1   introduction to cluster computing wit...
Alpine academy apache spark series #1 introduction to cluster computing wit...Holden Karau
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8InnovationM
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkitwlscaudill
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Synchronize applications with akeneo/batch
Synchronize applications with akeneo/batchSynchronize applications with akeneo/batch
Synchronize applications with akeneo/batchgplanchat
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & WebpackCodifly
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 

Similar to Reactive programming with RxJava (20)

Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Alpine academy apache spark series #1 introduction to cluster computing wit...
Alpine academy apache spark series #1   introduction to cluster computing wit...Alpine academy apache spark series #1   introduction to cluster computing wit...
Alpine academy apache spark series #1 introduction to cluster computing wit...
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
Enumerable
EnumerableEnumerable
Enumerable
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Synchronize applications with akeneo/batch
Synchronize applications with akeneo/batchSynchronize applications with akeneo/batch
Synchronize applications with akeneo/batch
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 

Recently uploaded

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
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
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Recently uploaded (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
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
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
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...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Reactive programming with RxJava

  • 1. Reactive Programming with RxJava Jobaer Chowdhury Technical Project Manager, Cefalo Presented @ JUGBD 6.0 (25/02/2017)
  • 2. Writing concurrent code in Java is hard.
  • 3. Writing correct concurrent code is even harder
  • 4. Unless you’ve read this from cover to cover, twice :-)
  • 6. What is RxJava? - A library for composing asynchronous and event based programs We can write concurrent code using RxJava library without worrying about low level threads, locks and synchronization.
  • 7. Brief history or Rx Reactive Extensions: first introduced by Microsoft RxJava: the jvm implementation was first developed by Netflix Current version is 2.x (I’ll talk about version 1.x here)
  • 8. RxJava: Most starred java repository on Github
  • 9.
  • 11. So let’s get started ...
  • 12. Observable<T> is the heart of RxJava
  • 13. Observable<T> … a flowing sequence of values … a stream of events An observer can subscribe to the Observable The Observable may call onNext(), onError() or onCompleted() on the observer
  • 15. We all know Iterables, right? Iterable<T> { Iterator<T> iterator(); } Iterator<T> { Boolean hasNext(); T next(); }
  • 16. Observable duality with Iterable Iterable<T>, Iterator<T> ● Get an iterator ● hasNext(), next() ● Pull based ● Sync Observable<T>, Observer<T> ● Subscribe an observer ● onNext(), onError(), onCompleted() ● Push based ● Async
  • 17. Observable<T> examples ● Observable<Tweet> ● Observable<Temperature> ● Observable<Person> ● Observable<HttpResponse> ● Observable<MouseEvent> ….. and so on
  • 18. Hello Observable! Let’s create an Observable<String> that will emit “Hello, world!” Observable<String> hello = Observable.create(obs -> { obs.onNext(“Hello, world!”); });
  • 19. And we can subscribe to it ... Observable<String> hello = Observable.create(obs -> { obs.onNext(“Hello, world!”); }); hello.subscribe(s -> { System.out.println(s); });
  • 20. We can simplify the creation here Observable<String> hello = Observable.just(“Hello, World!”);
  • 21. We can also handle errors and completed event Observable<String> hello = Observable.just(“Hello, World!”); hello.subscribe( val -> {System.out.println(val);}, error -> {System.out.println(“Error occurred”);}, () -> { System.out.println(“Completed”)}; })
  • 22. We’ve seen how we can create Observables, and how to consume them.
  • 23. Let’s see how we can modify/operate on Observables
  • 24.
  • 25. Observable.filter example Observable<Integer> numbers = Observable.just(1, 2, 3, 4, 5, 6); Observable<Integer> result = numbers.filter(num -> num % 2 == 0); // the result will contain 2, 4, 6 inside the Observables
  • 26.
  • 27. Observable.map example // We have a function that gives us an Observable of ints Observable<Integer> ids = searchForArticles(“dhaka”); // another function that takes an int, and returns an article Article loadArticle(Integer articleId) {...} Observable<Article> result = ids.map(id -> loadArticle(id));
  • 28.
  • 29. Observable.flatMap example // We have a function that gives us an Observable of ints Observable<Integer> ids = searchForArticles(“dhaka”); // and a function returns an article wrapped inside Observable Observable<Article> loadArticle(Integer articleId) {...} Observable<Article> result = ids.flatMap(id -> loadArticle(id));
  • 31. Map vs. flatMap example Observable<Integer> ids = searchForArticles(“dhaka”); Observable<Article> loadArticle(Integer articleId) {...} Observable<Observable<Article>> res = ids.map(this::loadArticle); Observable<Article> result = ids.flatMap(this::loadArticle);
  • 32.
  • 33. There are many more operators ...
  • 34. Let’s use Observables to solve a real world problem
  • 35. A real world example Let’s assume we are working for a news service. And we have the following requirements. ● Do a search for a term on the search server. The search server will return some ids ● For each id load the news article from db. ● For each id find out how many likes the article has on social network ● Merge the result from above two steps and send it to view layer
  • 36. Let’s assume we have the following (sync) API List<Integer> searchForArticles(String query) PersistentArticle loadArticle(Integer articleId) Integer fetchLikeCount(Integer articleId) …. and we can create article by using the db object and like count Article result = new Article(PersistentArticle, Integer)
  • 37. One way of solving it List<Integer> searchResult = searchForArticles(“dhaka”); List<Article> result = new ArrayList<>(); for(Integer id : searchResult) { PersistentArticle pa = loadArticle(id) Integer likes = fetchLikeCount(id) result.add(new Article(pa, likes)); } return result;
  • 38. Do you see any problem with this code?
  • 39. It’s sequential, and may take some time to run.
  • 40.
  • 41. When an article is loading, nothing prevents us from fetching the like count of that article, or loading another article, right?
  • 42.
  • 43. A concurrent solution may save us running time. And we can use Observables to do so.
  • 44. Let’s try to use Observables now
  • 45. Let’s assume now we have an async API Observable<Integer> searchForArticles(String query) Observable<PersistentArticle> loadArticle(Integer articleId) Observable<Integer> fetchLikeCount(Integer articleId) And we need to come up with the result as the following type. Observable<Article> result = … ; // We can use the result like following result.subscribe(article -> {//update the view with it});
  • 46. Don’t worry about how the async API was implemented. Just assume it is present. (If we only have a sync api, we can still make it async by wrapping things inside Observables, using Observable.create, just etc.)
  • 47. First step: do the search Observable<Integer> ids = searchForArticles(String query); …. For each id we need to load the article and fetch the like count.
  • 48. How do we get the ids out from the Observable?
  • 49. We don’t, instead we apply some operator to transform the source Observable to a different one
  • 50. Let’s go back to few slides ago, and see how we solved the problem sequentially
  • 51. The traditional solution ... List<Integer> searchResult = searchForArticles(“dhaka”); List<Article> result = new ArrayList<>(); for(Integer id : searchResult) { PersistentArticle pa = loadArticle(id) Integer likes = fetchLikeCount(id) result.add(new Article(pa, likes)); } return result;
  • 52.
  • 53. But we don’t do it like this in rx
  • 54.
  • 55. Many Observable operators take lambda as parameter. And we can get the item from inside the Observable box as a parameter of our supplied lambda.
  • 56. In case of Observable.filter Observable<Integer> numbers = Observable.just(1, 2, 3, 4, 5, 6); numbers.filter(num -> num % 2 == 0); // The Observable.filter operator takes a lambda as parameter // We pass it a lambda // Our supplied lambda will be called for each of the item // So here the parameter “num” will represent an item inside the box // This is how we get things out from Observable box.
  • 57. So, let’s get back to the original question Observable<Integer> ids = searchForArticles(String query); …. For each id we need to load the article and fetch the like count.
  • 58. Now we know we need to apply some operator, which one?
  • 59. We have to apply flatMap Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { // do something with the id ... }); So, by applying flatMap, we somehow get the item from inside the Observable box, as the parameter of our lambda.
  • 60. We have to apply flatMap Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { Observable<PersistentArticle> arts = loadArticle(id); Observable<Integer> likes = fetchLikeCount(id); //how do we get the article out from inside Observable? });
  • 61. We need to apply flatMap again ... Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { Observable<PersistentArticle> arts = loadArticle(id); Observable<Integer> likes = fetchLikeCount(id); return arts.flatMap(art -> { // and now we need to get the likes out }); })
  • 62. And flatMap again ... Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { Observable<PersistentArticle> arts = loadArticle(id); Observable<Integer> likes = fetchLikeCount(id); return arts.flatMap(art -> { return likes.flatMap(like -> { // now we have everything to make an Article object // so what do we return here? A new Article()? }); }); })
  • 63. We need to wrap the result inside Observable Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { Observable<PersistentArticle> arts = loadArticle(id); Observable<Integer> likes = fetchLikeCount(id); return arts.flatMap(art -> { return likes.flatMap(like -> { return Observable.just(new Article(art, like)); }); }); })
  • 64. We can remove some nesting here ...
  • 65.
  • 66. Alternate version using zip Observable<Integer> ids = searchForArticles(query); ids.flatMap(id -> { Observable<PersistentArticle> arts = loadArticle(id); Observable<Integer> likes = fetchLikeCount(id); return Observable.zip(arts, likes, (art, lc) -> { return new Article(art, lc); }); }); })
  • 67. Using the full power of Java 8 … searchForArticles(query).flatMap(id -> { return zip(loadArticle(id), fetchLikeCount(id), Article::new); }); });
  • 68. Using the full power of Java 8 … searchForArticles(query).flatMap(id -> { return zip(loadArticle(id), fetchLikeCount(id), Article::new); }); }); This is the solution we desire. I find this code beautiful. And it’s (mostly) concurrent (depending on the implementation of the search, load, etc.).
  • 69. Keep these in mind while using RxJava ● Observables can emit zero, one or more items ● Observables can be of infinite stream of values/events ● Observables can complete without returning anything, Observable.empty(). ● Observables can emit some items and then call onError() to terminate abnormally ● If onError() is called, then onCompleted will not be called
  • 70. Keep these in mind while using RxJava ● Observables are by default lazy. If no subscriber is subscribed, then nothing will be executed. ● By default they run in the same thread from which the subscriber is called ● You can change the subscriber thread by calling subscribeOn() ● You can change the observer thread by calling observeOn() ● There are some built in Schedulers (similar to thread pool). For example Schedulers.io(), Schedulers.computation(). ● A single Observable issues notifications to observers serially (not in parallel).
  • 71. A better version of the previous code searchForArticles(query).flatMap(id -> { return Observable.just(id) .subscribeOn(Schedulers.io()) .flatMap(i ->{ return zip(loadArticle(i), fetchLikeCount(i), Article::new); }); }); }); In fact this is the concurrent version, although it lost it’s beauty a bit :-) Hoping to cover this in a future session.
  • 72. When you have multiple async or concurrent things, depending on each other, RxJava may be a good candidate.
  • 73. I only covered the basics, there are way more to learn …
  • 74. Advanced topics (maybe in some future sessions) A whole lot more operators Subjects Schedulers Backpressure Implementing custom operators
  • 75. Have a look into ● CompletableFuture (introduced in java 8) ● Reactive streams specification (which RxJava 2.x implemented) ● java.util.concurrent.Flow api (coming in java 9)
  • 76. Reference ● Collection of all tutorials, http://reactivex.io/tutorials.html ● Reactive programming with RxJava book, http://shop.oreilly.com/product/0636920042228.do ● The RxJava contract, http://reactivex.io/documentation/contract.html