SlideShare a Scribd company logo
Introduction to RxJava for
Android
Esa Firman
What is RxJava?
RxJava is a Java VM implementation of ReactiveX (Reactive
Extensions): a library for composing asynchronous and
event-based programs by using observable sequences
See also: 2 minutes introduction to Rx
https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877#.rwup8ee0s
The Problem
How to deal with execution context ?
Threads
Handler handler = new Handler(Looper.getMainLooper());
new Thread(){
@Override
public void run() {
final String result = doHeavyTask();
handler.post(new Runnable() { // or runUIThread on Activity
@Override
public void run() {
showResult(result);
}
});
}
}.start();
Threads
Pros:
- Simple
Cons:
- Hard way to deliver results in UI thread
- Pyramid of Doom
AsyncTask
new AsyncTask<Void, Integer, String>(){
@Override
protected String doInBackground(Void... params) {
return doHeavyTask();
}
@Override
protected void onPostExecute(String s) {
showResult(s);
}
}.execute();
AsyncTask
Pros:
- Deal with main thread
Cons:
- Hard way to handling error
- Not bound to activity/fragment lifecycle
- Not composable
- Nested AsyncTask
- “Antek Async”
Why Rx?
- Because multithreading is hard
- Execution context
- Powerful operators
- Composable
- No Callback Hell
- Etc ...
The Basic
The basic building blocks of reactive code are Observables
and Subscribers. An Observable emits items; a Subscriber
consumes those items.
The smallest building block is actually an Observer, but in practice you are most often using Subscriber because that's how
you hook up to Observables.
The Basic
Observables often don't start emitting items until someone
explicitly subscribes to them
Enough talk, let’s see some code ...
Hello World
public Observable<String> getStrings() {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
subscriber.onNext("Hello, World");
subscriber.onCompleted();
} catch (Exception ex) {
subscriber.onError(ex);
}
}
});
}
Hello World
getStrings().subscribe(new Subscriber(){
@Override
public void onCompleted() {
// no - op
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(String s) {
System.out.println(s);
}
};
Observable<String> myObservable = Observable.just("Hello, world!");
Action1<String> onNextAction = new Action1<>() {
@Override
public void call(String s) {
System.out.println(s);
}
};
myObservable.subscribe(onNextAction);
// Outputs "Hello, world!"
Simpler Code
Simplest* Code - Using Lambda
Observable.just("Hello, World").subscribe(System.out::println);
*AFAIK
Observable Creation
Observable.create(Observable.onSubscribe)
from( ) — convert an Iterable or a Future or single value into an Observable
repeat( ) — create an Observable that emits a particular item or sequence of items repeatedly
timer( ) — create an Observable that emits a single item after a given delay
empty( ) — create an Observable that emits nothing and then completes
error( ) — create an Observable that emits nothing and then signals an error
never( ) — create an Observable that emits nothing at all
Operators
Filtering Operators
- filter( ) — filter items emitted by an Observable
- takeLast( ) — only emit the last n items emitted by an Observable
- takeLastBuffer( ) — emit the last n items emitted by an Observable, as a single list item
- skip( ) — ignore the first n items emitted by an Observable
- take( ) — emit only the first n items emitted by an Observable
- first( ) — emit only the first item emitted by an Observable, or the first item that meets some condition
- elementAt( ) — emit item n emitted by the source Observable
- timeout( ) — emit items from a source Observable, but issue an exception if no item is emitted in a
specified timespan
- distinct( ) — suppress duplicate items emitted by the source Observable
Introduction to rx java for android
Filter
Observable.just("Esa", "Ganteng", "Jelek")
.filter(s -> !s.equalsIgnoreCase("jelek"))
.buffer(2)
.subscribe(strings -> {
print(strings.get(0) + “ “ + strings.get(1));
});
// print Esa Ganteng
Transformation Operators
- map( ) — transform the items emitted by an Observable by applying a function to each of them
- flatMap( ) — transform the items emitted by an Observable into Observables, then flatten this into a
single Observable
- scan( ) — apply a function to each item emitted by an Observable, sequentially, and emit each
successive value
- groupBy( ) and groupByUntil( ) — divide an Observable into a set of Observables that emit groups of
items from the original Observable, organized by key
- buffer( ) — periodically gather items from an Observable into bundles and emit these bundles rather
than emitting the items one at a time
- window( ) — periodically subdivide items from an Observable into Observable windows and emit these
windows rather than emitting the items one at a time
Introduction to rx java for android
Map
Observable.from(Arrays.asList("Esa", "Esa", "Esa"))
.map(s -> s + " ganteng")
.subscribe(System.out::println);
// print Esa ganteng 3 times
Introduction to rx java for android
FlatMap
Observable.just( Arrays.asList("Tiramisu", "Black Forest", "Black Mamba"))
.flatMap(Observable::from)
.map(String::length)
.subscribe(System.out::print);
// print 8,11,12
Confused?
Getting map/flatMap/compose mixed up? Think types:
map : T -> R
flatMap : T -> Observable<R>
compose : Observable<T> -> Observable<R>
#ProTips
Retrofit Integration
@GET("mobile_detail_calc_halte_trans.php")
Observable<List<HalteDetail>>
getHalteDetails(@Query("coridor") String coridor);
mApiService.getHalteDetails(halte.getCoridor())
.observeOn(AndroidSchedulers.mainThread())
.doOnTerminate(this::resetUILoading)
.subscribe(halteDetails -> {
if (halteDetails != null) {
setMarker(halteDetails);
}
});
More Examples
mApiService.getCommentList()
.compose(bindToLifecycle())
.compose(applyApiCall())
.doOnTerminate(this::stopLoading)
.subscribe(comments -> {
if (comments != null)
mCommentAdapter.pushData(comments);
});
More Samples
Observable<Bitmap> imageObservable = Observable.create(observer -> {
Bitmap bm = downloadBitmap();
return bm;
});
imageObservable.subscribe(image -> loadToImageView(image));
// blocking the UI thread
imageObservable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(image -> loadToImageView(image));
// non blocking but also execute loadToImageView on UI Thread
More Examples
public Observable<List<Area>> getAreas() {
Observable<List<Area>> network = mApiService.getArea()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(areas -> saveAreas(areas));
Observable<List<Area>> cache = getAreasFromLocal();
return Observable.concat(cache, network).first(areas -> areas != null);
}
More Examples (Again)
public void onLocationChanged(Location location) {
onLocationChanged.onNext(location);
}
mGmsLocationManager.onLocationChanged
.throttleLast(10, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(location -> {
mPrensenter.updateMyLocation(location);
});
FAQ
1. Should we still use Thread and AsyncTask?
2. Where to start?
Third Party Implementation
- Android ReactiveLocation https://github.com/mcharmas/Android-
ReactiveLocation
- RxPermissions
https://github.com/tbruyelle/RxPermissions
- RxBinding
https://github.com/JakeWharton/RxBinding
- SQLBrite
https://github.com/square/sqlbrite
- RxLifeCycle
https://github.com/trello/RxLifecycle
Links
- http://slides.com/yaroslavheriatovych/frponandroid
- https://github.com/Netflix/RxJava/
- https://github.com/orfjackal/retrolambda
- https://github.com/evant/gradle-retrolambda
- http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html
- https://github.com/Netflix/RxJava/wiki
Questions?

More Related Content

PDF
Reactive programming on Android
PDF
Practical RxJava for Android
PDF
Practical RxJava for Android
PDF
Reactive programming with RxJava
PDF
RxJava from the trenches
PPTX
An Introduction to RxJava
PDF
Rxjava meetup presentation
PDF
Intro to RxJava/RxAndroid - GDG Munich Android
Reactive programming on Android
Practical RxJava for Android
Practical RxJava for Android
Reactive programming with RxJava
RxJava from the trenches
An Introduction to RxJava
Rxjava meetup presentation
Intro to RxJava/RxAndroid - GDG Munich Android

What's hot (20)

PDF
Building Scalable Stateless Applications with RxJava
PDF
RxJava 2.0 介紹
PDF
Rxjava 介紹與 Android 中的 RxJava
PDF
Non Blocking I/O for Everyone with RxJava
PPTX
RxJava Applied
PDF
RxJava on Android
PDF
Reactive programming on Android
PDF
GKAC 2015 Apr. - RxAndroid
PDF
RxJava applied [JavaDay Kyiv 2016]
PDF
Reactive Android: RxJava and beyond
PDF
Introduction to Retrofit and RxJava
PPTX
Reactive programming with RxAndroid
PPTX
Rx java in action
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PDF
AWS Java SDK @ scale
PPTX
PDF
Parallel streams in java 8
PDF
Kotlin Receiver Types 介紹
PDF
RxJava in practice
PPTX
Angular2 rxjs
Building Scalable Stateless Applications with RxJava
RxJava 2.0 介紹
Rxjava 介紹與 Android 中的 RxJava
Non Blocking I/O for Everyone with RxJava
RxJava Applied
RxJava on Android
Reactive programming on Android
GKAC 2015 Apr. - RxAndroid
RxJava applied [JavaDay Kyiv 2016]
Reactive Android: RxJava and beyond
Introduction to Retrofit and RxJava
Reactive programming with RxAndroid
Rx java in action
Functional Reactive Programming (FRP): Working with RxJS
AWS Java SDK @ scale
Parallel streams in java 8
Kotlin Receiver Types 介紹
RxJava in practice
Angular2 rxjs
Ad

Viewers also liked (17)

PDF
Google Guava - Core libraries for Java & Android
PPTX
Reactive Programming on Android - RxAndroid - RxJava
PPTX
2 презентация rx java+android
PDF
RxJava + Retrofit
PDF
Dagger & rxjava & retrofit
PDF
RxJava for Android - GDG and DataArt
PDF
Rx java x retrofit
PDF
The Mayans Lost Guide to RxJava on Android
PDF
Retrofit Android by Chris Ollenburg
PDF
RxJava for Android - GDG DevFest Ukraine 2015
PDF
Android antipatterns
PDF
RxBinding-kotlin
PDF
Retrofit
PDF
Google guava - almost everything you need to know
PDF
RxJava on Android
PDF
Kotlinにお触り
PPTX
Headless fragments in Android
Google Guava - Core libraries for Java & Android
Reactive Programming on Android - RxAndroid - RxJava
2 презентация rx java+android
RxJava + Retrofit
Dagger & rxjava & retrofit
RxJava for Android - GDG and DataArt
Rx java x retrofit
The Mayans Lost Guide to RxJava on Android
Retrofit Android by Chris Ollenburg
RxJava for Android - GDG DevFest Ukraine 2015
Android antipatterns
RxBinding-kotlin
Retrofit
Google guava - almost everything you need to know
RxJava on Android
Kotlinにお触り
Headless fragments in Android
Ad

Similar to Introduction to rx java for android (20)

PPTX
Intro to Reactive Thinking and RxJava 2
PPTX
RxJava2 Slides
PDF
RxJava@Android
PDF
Saving lives with rx java
PPTX
Reactive programming with rx java
PDF
How to Think in RxJava Before Reacting
PPTX
Rxandroid
PPTX
RxAndroid
PDF
RxJava@DAUG
PPTX
Introduction to RxJava on Android
PDF
RxJava pour Android : présentation lors du GDG Android Montréal
PPTX
Intro to Functional Programming with RxJava
PPTX
RxJava 2 Reactive extensions for the JVM
PPTX
Reactive Programming on Android
PPTX
Reactive Java (33rd Degree)
PDF
Reactive Functional Programming with Java 8 on Android N
PPTX
Rx presentation
PPTX
Rxjs swetugg
PDF
Functional Reactive Programming with Kotlin on Android - Giorgio Natili - Cod...
PDF
RxJava и Android. Плюсы, минусы, подводные камни
Intro to Reactive Thinking and RxJava 2
RxJava2 Slides
RxJava@Android
Saving lives with rx java
Reactive programming with rx java
How to Think in RxJava Before Reacting
Rxandroid
RxAndroid
RxJava@DAUG
Introduction to RxJava on Android
RxJava pour Android : présentation lors du GDG Android Montréal
Intro to Functional Programming with RxJava
RxJava 2 Reactive extensions for the JVM
Reactive Programming on Android
Reactive Java (33rd Degree)
Reactive Functional Programming with Java 8 on Android N
Rx presentation
Rxjs swetugg
Functional Reactive Programming with Kotlin on Android - Giorgio Natili - Cod...
RxJava и Android. Плюсы, минусы, подводные камни

Recently uploaded (20)

PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Nekopoi APK 2025 free lastest update
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
System and Network Administration Chapter 2
PPTX
history of c programming in notes for students .pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PTS Company Brochure 2025 (1).pdf.......
Nekopoi APK 2025 free lastest update
Which alternative to Crystal Reports is best for small or large businesses.pdf
Why Generative AI is the Future of Content, Code & Creativity?
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
CHAPTER 2 - PM Management and IT Context
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Designing Intelligence for the Shop Floor.pdf
System and Network Administration Chapter 2
history of c programming in notes for students .pptx
Odoo POS Development Services by CandidRoot Solutions
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Computer Software and OS of computer science of grade 11.pptx
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Design an Analysis of Algorithms I-SECS-1021-03
Wondershare Filmora 15 Crack With Activation Key [2025

Introduction to rx java for android

  • 1. Introduction to RxJava for Android Esa Firman
  • 2. What is RxJava? RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences See also: 2 minutes introduction to Rx https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877#.rwup8ee0s
  • 3. The Problem How to deal with execution context ?
  • 4. Threads Handler handler = new Handler(Looper.getMainLooper()); new Thread(){ @Override public void run() { final String result = doHeavyTask(); handler.post(new Runnable() { // or runUIThread on Activity @Override public void run() { showResult(result); } }); } }.start();
  • 5. Threads Pros: - Simple Cons: - Hard way to deliver results in UI thread - Pyramid of Doom
  • 6. AsyncTask new AsyncTask<Void, Integer, String>(){ @Override protected String doInBackground(Void... params) { return doHeavyTask(); } @Override protected void onPostExecute(String s) { showResult(s); } }.execute();
  • 7. AsyncTask Pros: - Deal with main thread Cons: - Hard way to handling error - Not bound to activity/fragment lifecycle - Not composable - Nested AsyncTask - “Antek Async”
  • 8. Why Rx? - Because multithreading is hard - Execution context - Powerful operators - Composable - No Callback Hell - Etc ...
  • 9. The Basic The basic building blocks of reactive code are Observables and Subscribers. An Observable emits items; a Subscriber consumes those items. The smallest building block is actually an Observer, but in practice you are most often using Subscriber because that's how you hook up to Observables.
  • 10. The Basic Observables often don't start emitting items until someone explicitly subscribes to them
  • 11. Enough talk, let’s see some code ...
  • 12. Hello World public Observable<String> getStrings() { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { try { subscriber.onNext("Hello, World"); subscriber.onCompleted(); } catch (Exception ex) { subscriber.onError(ex); } } }); }
  • 13. Hello World getStrings().subscribe(new Subscriber(){ @Override public void onCompleted() { // no - op } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(String s) { System.out.println(s); } };
  • 14. Observable<String> myObservable = Observable.just("Hello, world!"); Action1<String> onNextAction = new Action1<>() { @Override public void call(String s) { System.out.println(s); } }; myObservable.subscribe(onNextAction); // Outputs "Hello, world!" Simpler Code
  • 15. Simplest* Code - Using Lambda Observable.just("Hello, World").subscribe(System.out::println); *AFAIK
  • 16. Observable Creation Observable.create(Observable.onSubscribe) from( ) — convert an Iterable or a Future or single value into an Observable repeat( ) — create an Observable that emits a particular item or sequence of items repeatedly timer( ) — create an Observable that emits a single item after a given delay empty( ) — create an Observable that emits nothing and then completes error( ) — create an Observable that emits nothing and then signals an error never( ) — create an Observable that emits nothing at all
  • 18. Filtering Operators - filter( ) — filter items emitted by an Observable - takeLast( ) — only emit the last n items emitted by an Observable - takeLastBuffer( ) — emit the last n items emitted by an Observable, as a single list item - skip( ) — ignore the first n items emitted by an Observable - take( ) — emit only the first n items emitted by an Observable - first( ) — emit only the first item emitted by an Observable, or the first item that meets some condition - elementAt( ) — emit item n emitted by the source Observable - timeout( ) — emit items from a source Observable, but issue an exception if no item is emitted in a specified timespan - distinct( ) — suppress duplicate items emitted by the source Observable
  • 20. Filter Observable.just("Esa", "Ganteng", "Jelek") .filter(s -> !s.equalsIgnoreCase("jelek")) .buffer(2) .subscribe(strings -> { print(strings.get(0) + “ “ + strings.get(1)); }); // print Esa Ganteng
  • 21. Transformation Operators - map( ) — transform the items emitted by an Observable by applying a function to each of them - flatMap( ) — transform the items emitted by an Observable into Observables, then flatten this into a single Observable - scan( ) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value - groupBy( ) and groupByUntil( ) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key - buffer( ) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time - window( ) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time
  • 23. Map Observable.from(Arrays.asList("Esa", "Esa", "Esa")) .map(s -> s + " ganteng") .subscribe(System.out::println); // print Esa ganteng 3 times
  • 25. FlatMap Observable.just( Arrays.asList("Tiramisu", "Black Forest", "Black Mamba")) .flatMap(Observable::from) .map(String::length) .subscribe(System.out::print); // print 8,11,12
  • 26. Confused? Getting map/flatMap/compose mixed up? Think types: map : T -> R flatMap : T -> Observable<R> compose : Observable<T> -> Observable<R> #ProTips
  • 27. Retrofit Integration @GET("mobile_detail_calc_halte_trans.php") Observable<List<HalteDetail>> getHalteDetails(@Query("coridor") String coridor); mApiService.getHalteDetails(halte.getCoridor()) .observeOn(AndroidSchedulers.mainThread()) .doOnTerminate(this::resetUILoading) .subscribe(halteDetails -> { if (halteDetails != null) { setMarker(halteDetails); } });
  • 29. More Samples Observable<Bitmap> imageObservable = Observable.create(observer -> { Bitmap bm = downloadBitmap(); return bm; }); imageObservable.subscribe(image -> loadToImageView(image)); // blocking the UI thread imageObservable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(image -> loadToImageView(image)); // non blocking but also execute loadToImageView on UI Thread
  • 30. More Examples public Observable<List<Area>> getAreas() { Observable<List<Area>> network = mApiService.getArea() .observeOn(AndroidSchedulers.mainThread()) .doOnNext(areas -> saveAreas(areas)); Observable<List<Area>> cache = getAreasFromLocal(); return Observable.concat(cache, network).first(areas -> areas != null); }
  • 31. More Examples (Again) public void onLocationChanged(Location location) { onLocationChanged.onNext(location); } mGmsLocationManager.onLocationChanged .throttleLast(10, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(location -> { mPrensenter.updateMyLocation(location); });
  • 32. FAQ 1. Should we still use Thread and AsyncTask? 2. Where to start?
  • 33. Third Party Implementation - Android ReactiveLocation https://github.com/mcharmas/Android- ReactiveLocation - RxPermissions https://github.com/tbruyelle/RxPermissions - RxBinding https://github.com/JakeWharton/RxBinding - SQLBrite https://github.com/square/sqlbrite - RxLifeCycle https://github.com/trello/RxLifecycle
  • 34. Links - http://slides.com/yaroslavheriatovych/frponandroid - https://github.com/Netflix/RxJava/ - https://github.com/orfjackal/retrolambda - https://github.com/evant/gradle-retrolambda - http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html - https://github.com/Netflix/RxJava/wiki