SlideShare une entreprise Scribd logo
1  sur  35
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
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
Map
Observable.from(Arrays.asList("Esa", "Esa", "Esa"))
.map(s -> s + " ganteng")
.subscribe(System.out::println);
// print Esa ganteng 3 times
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?

Contenu connexe

Tendances

Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
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
 
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
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaFabio Collini
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kros Huang
 

Tendances (20)

Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
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
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
 
RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 

En vedette

Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
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 + Retrofit
RxJava + RetrofitRxJava + Retrofit
RxJava + RetrofitDev2Dev
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofitTed Liang
 
RxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtRxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtConstantine Mars
 
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
 
Retrofit Android by Chris Ollenburg
Retrofit Android by Chris OllenburgRetrofit Android by Chris Ollenburg
Retrofit Android by Chris OllenburgTrey Robinson
 
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
 
Retrofit
RetrofitRetrofit
Retrofitbresiu
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Androidyo_waka
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in AndroidAli Muzaffar
 

En vedette (17)

Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
RxJava + Retrofit
RxJava + RetrofitRxJava + Retrofit
RxJava + Retrofit
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofit
 
RxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtRxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArt
 
Rx java x retrofit
Rx java x retrofitRx java x retrofit
Rx java x retrofit
 
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
 
Retrofit Android by Chris Ollenburg
Retrofit Android by Chris OllenburgRetrofit Android by Chris Ollenburg
Retrofit Android by Chris Ollenburg
 
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
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
RxBinding-kotlin
RxBinding-kotlinRxBinding-kotlin
RxBinding-kotlin
 
Retrofit
RetrofitRetrofit
Retrofit
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Kotlinにお触り
Kotlinにお触りKotlinにお触り
Kotlinにお触り
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in Android
 

Similaire à Introduction to rx java for android

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
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensionsMarcin Juraszek
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivediharintrivedi
 
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
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVMNetesh Kumar
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTVasil Remeniuk
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptChanghwan Yi
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfaromalcom
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8Berk Soysal
 
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
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 

Similaire à Introduction to rx java for android (20)

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
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensions
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
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
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWT
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascript
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
 
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
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 

Dernier

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Dernier (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

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
  • 19.
  • 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
  • 22.
  • 23. Map Observable.from(Arrays.asList("Esa", "Esa", "Esa")) .map(s -> s + " ganteng") .subscribe(System.out::println); // print Esa ganteng 3 times
  • 24.
  • 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