SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Introduce RxJava and Android
Author: Đới Thanh Thịnh
Savvycom-software
Introduction
1. Developing a complex Android app that has lots of
network connections, user interactions, and animations
often means writing code that is full of nested
callbacks.
2. Sometimes called callback hell, is not only lengthy and
hard to understand, hard to maintain.
3. ReactiveX offers an alternative approach that is both
clear and concise, to manage asynchronous tasks and
events.
Overview
 1. What is ReactiveX?
 2. Observables, Observers
 3. Operator
 4. Schedulers
 5. Retrofit with RxAndroid
What is ReactiveX?
 ReactiveX is a library for composing
asynchronous and event-based programs by using
observable sequences.
 RxJava, which is a port of the Reactive Extensions
library from .NET, enables Android apps to be
built in this style.
Async programming
 Nowadays programming in an imperative single threaded way
usually leads to strange behaviors, blocking non responsive
UIs and therefore a bad user experience.
 This can be avoided by handling unpredicted things
asynchronously. For example actively waiting for a database
query or a webservice call can cause an application freeze, if
the network is not responsive.
Async programming
public List<Todo> getTodos() {
List<Todo> todosFromWeb
= // query a webservice (with bad
network latency)
return todosFromDb;
}
public void
getTodos(Consumer<List<Todo>>
todosConsumer) {
Thread thread = new Thread(()-> {
List<Todo> todosFromWeb = //
query a webservice
todosConsumer.accept(todosFromWeb);
});
thread.start();
}
Setup
Setup your app/build.gradle:
dependencies {
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.4'
}
Observables, Observers and
Subscriptions
1. Observables
 Emit items (Objects, Strings, Integers etc.).
 Does not start emitting till someone subscribes.
2. Observers
 To watch Observables by subscribing to them and consumes data
3. Manipulation operators (this is the “functional programming” part)
 Transforms
 Filters
 Etc.
 The observable we just created will emit its data only when it has at least one
observer.
 Similar to the observer pattern. Except, doesn’t start emitting till there is a subscriber.
Creating Observable
 RxJava provides several methods to create an
observable.
 Observable.just() - Allows to create an observable as
wrapper around other data types
 Observable.from() - takes a collection or an array and
emits their values in their order in the data structure
 Observable.fromCallable() - Allows to create an
observable for a Callable`
 To create observers:
 Implement Action1 - Allow you to create a simple observer
which has a call methods. This method is called if a new
object is emitted.
Defining Observables
// Observables emit any number of items to be processed
// The type of the item to be processed needs to be specified as a "generic type"
// In this case, the item type is `String`
Observable<String> myObservable = Observable.create(
new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> sub) {
// "Emit" any data to the subscriber
sub.onNext("a");
sub.onNext("b");
sub.onNext("c");
// Trigger the completion of the event
sub.onCompleted();
}
}
);
This observable event emits the data “a”, “b”, “c” and then completes.
Defining Observers
Observer<String> mySubscriber = new Observer<String>() {
// Triggered for each emitted value
@Override
public void onNext(String s) { System.out.println("onNext: " + s); }
// Triggered once the observable is complete
@Override
public void onCompleted() { System.out.println("done!"); }
// Triggered if there is any errors during the event
@Override
public void onError(Throwable e) { }
};
Now let’s create a Observer to consume this emitted data from the
Observable:
Subscribing to Observables
 An Observer can be attached to an Observable in order to
respond to emitted data with:
• // Attaches the subscriber above to the observable object
• myObservable.subscribe(mySubscriber);
Outputs:
// onNext: "a"
// onNext: "b"
// onNext: "c"
// done!
Observable Observers
Subscribing to Observables
 void onNext(T t):
 Provides the Observer with a new item to observe.
 may call this method 0 or more times.
 will not call this method again after it calls either onCompleted or
onError
 void onCompleted():
 Notifies the Observer that the Observable has finished sending push-based
notifications.
 void onError(Throwable e):
Notifies the Observer that the Observable has experienced an error
condition.
 Subscription subscribe(final Observer<? super T> observer):
 Subscribes to an Observable and provides an Observer that implements
functions to handle the items the Observable emits and any error or
completion
Operator
 Just — convert an object or a set of objects into an Observable that
emits that or those objects
Observable.just(1, 2, 3).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("Complete!");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext!");
}
});
System.out: onNext!: 1
System.out: onNext!: 2
System.out: onNext!: 3
System.out: Complete!
Operator
 From — Converts an Array into an Observable that emits the items
in the Array.
Integer[] items = {0, 1, 2, 3, 4};
Observable.from(items).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("Complete!");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext from!" + integer);
}
});
System.out: onNext!0
System.out: onNext!1
System.out: onNext!2
System.out: onNext!3
System.out: onNext!4
System.out: Complete!
Operator
 Filter : Filters items emitted by an Observable by only emitting
those that satisfy a specified predicate.
Observable.just(1, 2, 3, 4, 5)
.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
return integer < 4;
}
}).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("Complete!");
}
@Override
public void onError(Throwable e) {
System.out.println("onError!");
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext just!" + integer);
}
});
System.out: onNext!0
System.out: onNext!1
System.out: onNext!2
System.out: onNext!3
System.out: Complete!
Operator
 Map: Transform the items emitted by an Observable by applying a
function to each item
Observable.just(1, 2, 3, 4, 5)
.map(new Func1<Integer, Integer>() {
@Override
public Integer call(Integer integer) {
return integer * 10;
}
}).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("Complete!");
}
@Override
public void onError(Throwable e) {
System.out.println("onError!");
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext!" + integer);
}
});
System.out: onNext! 10
System.out: onNext! 20
System.out: onNext! 30
System.out: onNext! 40
System.out: onNext! 50
System.out: Complete!
Operator – Many Others
 http://reactivex.io/documentation/operators.html
 Operators By Category
 Creating Observables: Create, Just …
 Transforming Observables: Map, FlatMap, …
 Filtering Observables: First , Filter , …
 Combining Observables: Join , Merge ,…
 Error Handling Operators: Catch , Retry
 Observable Utility Operators:Subscribe, SubscribeOn
 Conditional and Boolean Operators:Contains, …
 Mathematical and Aggregate Operators:Average, Count
Schedulers
 RxJava is synchronous by default, but work can be defined
asynchronously using schedulers. For instance, we can define that
the network call should be done on a background thread, but the
callback should be done on the main UI thread.
Observable.from(doLongNetwork())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver())
1. Observable
2.Schedulers
3. Observer
Schedulers
These schedulers than then be used to control which thread an observable or
the subscriber are operating on using the subscribeOn() and observeOn()
Schedulers
 subscribeOn():
Basic rules of rxjava threading:
1. rxjava is single threaded by default
2. subscribeOn only affects upstream
3. only the subscribeOn closest to the source matters
4. observeOn only affects downstream
Schedulers
1. rxjava is single threaded by default
When you do not use observeOn, subscribeOn, or an operator that runs on a particular
scheduler , the callback will be receieved on the thread subscribe happened on.
2. subscribeOn only affects upstream
getANumberObservable()
.subscribeOn(Schedulers.io())
.map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
Log.i("Operator thread", Thread.currentThread().getName());
return String.valueOf(integer);
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i("Subscriber thread", Thread.currentThread().getName() + " onNext: " +
s);
}
});
Output:
Observable thread: RxIoScheduler-2
Operator thread: RxIoScheduler-2
Subscriber thread: RxIoScheduler-2
onNext: 1
Schedulers
3. Only the subscribeOn closest to the source matters:
Observable.just("Some String")
.map(new Func1<String, Integer>() {
@Override
public Integer call(String s) {
return s.length();
}
})
.subscribeOn(Schedulers.computation()) // changing to computation
.subscribeOn(Schedulers.io()) // won’t change the thread to IO
.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext!" + integer);
Log.d("onNext", "Number " + integer + " Thread: " + Thread.currentThread().getName());
}
});
Output
System.out: onNext!11 onNext:
Number 11
Thread: RxComputationScheduler-1
Schedulers
4. observeOn only affects downstream
ObserveOn function () pass an argument is a Scheduler will make the
Operator and Subscriber called behind it is running on thread
provided by this Scheduler.
observeOn
getANumberObservable()
//.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
Log.i("Operator thread", Thread.currentThread().getName());
return String.valueOf(integer);
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i("Subscriber thread", Thread.currentThread().getName() +
" onNext: " + s);
}
});
Output
Observable thread: main
Operator thread: RxNewThreadScheduler-1
Subscriber thread: RxNewThreadScheduler-
1 onNext: 1
Deferring Observable
Create(…): actually creates Observable immediately.
public final static <T> Observable<T> create(OnSubscribe<T> f) {
return new Observable<T>(hook.onCreate(f));
}
Defer(…): creates Observable only when subscriber subscribes, create a
new Observable each time you get a subscriber.
public final static <T> Observable<T> defer(Func0<Observable<T>>
observableFactory) {
return create(new OnSubscribeDefer<T>(observableFactory));
}
Deferring Observable
SomeType instance = new SomeType();
Observable<String> value = instance.valueObservable();
instance.setValue("Some Value");
value.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
Log.d("Thinhdt", "Defer Observable: " + s);
}
});
Output:
Thinhdt: Defer Observable: null
Deferring Observable : Solution
public Observable<String> valueObservable() {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext(value);
subscriber.onCompleted(); }
});
}
Observable.cr
eate()
public Observable<String> valueObservable() {
return Observable.defer(new Func0<Observable<String>>() {
@Override
public Observable<String> call() {
return Observable.just(value);
}
});
}
Observable.
defer
Replacing AsyncTask with Observables
// This constructs an `Observable` to download the image
public Observable<Bitmap> getImageNetworkCall() {
// Insert network call here!
}
// Construct the observable and use `subscribeOn` and `observeOn`
// This controls which threads are used for processing and observing
Subscription subscription = getImageNetworkCall()
// Specify the `Scheduler` on which an Observable will operate
.subscribeOn(Schedulers.io())
// Specify the `Scheduler` on which a subscriber will observe this `Observable`
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Bitmap>() {
// This replaces `onPostExecute(Bitmap bitmap)`
@Override
public void onNext(Bitmap bitmap) {
// Handle result of network request
}
@Override
public void onCompleted() {
// Update user interface if needed
}
@Override
public void onError() {
// Update user interface to handle error
}
});
1. Thread to perform the task in the
background used subscribeOn()
2. To update UI on main thread used
observeOn()
Retrofit with RxAndroid
1. public interface MyApiEndpointInterface {
@GET("/users/{username}")
Observable<User> getUser(@Path("username") String
username);
}
2. MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
// Get the observable User object
Observable<User> call = apiService.getUser(username);
// To define where the work is done, we can use `observeOn()` with Retrofit
// This means the result is handed to the subscriber on the main thread
call.observeOn(AndroidSchedulers.mainThread()).subscribe(new
Subscriber<User>() {
@Override
public void onNext(User user) {
// Called once the `User` object is available
}
@Override
public void onCompleted() {
// Nothing to do here
}
@Override
public void onError(Throwable e) {
// cast to retrofit.HttpException to get the response code
if (e instanceof HttpException) {
HttpException response;
int code = response.code();
}
}
});
Resources:
 https://hackmd.io/s/BkITYDZf
 http://www.slideshare.net/penano/rx-javasc
 http://reactivex.io
 http://www.vogella.com/tutorials/RxJava/article.html
 http://randomdotnext.com/retrofit-rxjava/
 http://blog.danlew.net/2015/07/23/deferring-observable-code-
until-subscription-in-rxjava/
 https://github.com/ruler88/GithubDemo
https://github.com/thinhdt/DemoRxAndroid/
https://github.com/thinhdt/Retrofit-RxAndroid

Weitere ähnliche Inhalte

Was ist angesagt?

Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseMarina Coelho
 
Server driven user interface (sdui) – framework for i os applications!
Server driven user interface (sdui) – framework for i os applications!Server driven user interface (sdui) – framework for i os applications!
Server driven user interface (sdui) – framework for i os applications!Azilen Technologies Pvt. Ltd.
 
State management
State managementState management
State managementIblesoft
 
Scriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the SillScriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the SillMario Heiderich
 
Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Darío Kondratiuk
 
Présentation de la Plateforme Nuxeo
Présentation de la Plateforme NuxeoPrésentation de la Plateforme Nuxeo
Présentation de la Plateforme NuxeoNuxeo
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012Sylvain Maret
 

Was ist angesagt? (20)

SQL Server vs Postgres
SQL Server vs PostgresSQL Server vs Postgres
SQL Server vs Postgres
 
Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and Firebase
 
Presentation SOAP
 Presentation SOAP Presentation SOAP
Presentation SOAP
 
Server driven user interface (sdui) – framework for i os applications!
Server driven user interface (sdui) – framework for i os applications!Server driven user interface (sdui) – framework for i os applications!
Server driven user interface (sdui) – framework for i os applications!
 
State management
State managementState management
State management
 
Spring security
Spring securitySpring security
Spring security
 
Scriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the SillScriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the Sill
 
Android volley
Android volleyAndroid volley
Android volley
 
Os Raysmith
Os RaysmithOs Raysmith
Os Raysmith
 
Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018
 
Présentation de la Plateforme Nuxeo
Présentation de la Plateforme NuxeoPrésentation de la Plateforme Nuxeo
Présentation de la Plateforme Nuxeo
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Variable hoisting in JavaScript
Variable hoisting in JavaScriptVariable hoisting in JavaScript
Variable hoisting in JavaScript
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
cours-gratuit.com--id-4422.pdf
cours-gratuit.com--id-4422.pdfcours-gratuit.com--id-4422.pdf
cours-gratuit.com--id-4422.pdf
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012
Securite des Web Services (SOAP vs REST) / OWASP Geneva dec. 2012
 
Marzouk jsp
Marzouk jspMarzouk jsp
Marzouk jsp
 

Andere mochten auch

КВН "Алгоритмы вокруг нас"
КВН "Алгоритмы вокруг нас"КВН "Алгоритмы вокруг нас"
КВН "Алгоритмы вокруг нас"svetlanamur
 
Comverse-EANTC-DMM-Policy-Manager-Report
Comverse-EANTC-DMM-Policy-Manager-ReportComverse-EANTC-DMM-Policy-Manager-Report
Comverse-EANTC-DMM-Policy-Manager-ReportNati Braha
 
Brianna Abregano Final Professional Persona Project
Brianna Abregano Final Professional Persona ProjectBrianna Abregano Final Professional Persona Project
Brianna Abregano Final Professional Persona ProjectBriannaAbregano
 
Kombinationsvæg version 1.1
Kombinationsvæg version 1.1Kombinationsvæg version 1.1
Kombinationsvæg version 1.1Kim Iversen
 
WEEE Management Policy Update from Thailand
WEEE Management Policy Update from ThailandWEEE Management Policy Update from Thailand
WEEE Management Policy Update from ThailandKeep Thailand Beautiful
 
Electrical technician
Electrical technicianElectrical technician
Electrical techniciantanweer alam
 
Curriculum vitae
Curriculum vitaeCurriculum vitae
Curriculum vitaeerika3105
 
En quran trans (sahih international).sahih
En quran trans (sahih international).sahihEn quran trans (sahih international).sahih
En quran trans (sahih international).sahihAbu Qasim
 
case study-ppt-2
case study-ppt-2case study-ppt-2
case study-ppt-2Neha Kumari
 
pointeur laser vert puissant 200mw Laser 303
pointeur laser vert puissant 200mw Laser 303pointeur laser vert puissant 200mw Laser 303
pointeur laser vert puissant 200mw Laser 303hannahjanelle
 
Роман Гуляк "SMALL THINGS THAT MATTER"
Роман Гуляк "SMALL THINGS THAT MATTER"Роман Гуляк "SMALL THINGS THAT MATTER"
Роман Гуляк "SMALL THINGS THAT MATTER"Agile Ukraine
 
social media analytics
social media analyticssocial media analytics
social media analyticsNeha Kumari
 
2015 16combinepdf
2015 16combinepdf2015 16combinepdf
2015 16combinepdfmadhesi
 
Marva play august 27 2015
Marva play august 27 2015Marva play august 27 2015
Marva play august 27 2015Marva Motton
 
laser bleu 1000mw puissant à forte vente pas cher
laser bleu 1000mw puissant à forte vente pas cherlaser bleu 1000mw puissant à forte vente pas cher
laser bleu 1000mw puissant à forte vente pas cherhannahjanelle
 
Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4heartfulness
 
Kaizen Mini Habits by Nataliya Trenina for IT Weekend
Kaizen Mini Habits by Nataliya Trenina for IT WeekendKaizen Mini Habits by Nataliya Trenina for IT Weekend
Kaizen Mini Habits by Nataliya Trenina for IT WeekendAgile Ukraine
 

Andere mochten auch (20)

КВН "Алгоритмы вокруг нас"
КВН "Алгоритмы вокруг нас"КВН "Алгоритмы вокруг нас"
КВН "Алгоритмы вокруг нас"
 
Comverse-EANTC-DMM-Policy-Manager-Report
Comverse-EANTC-DMM-Policy-Manager-ReportComverse-EANTC-DMM-Policy-Manager-Report
Comverse-EANTC-DMM-Policy-Manager-Report
 
Brianna Abregano Final Professional Persona Project
Brianna Abregano Final Professional Persona ProjectBrianna Abregano Final Professional Persona Project
Brianna Abregano Final Professional Persona Project
 
Kombinationsvæg version 1.1
Kombinationsvæg version 1.1Kombinationsvæg version 1.1
Kombinationsvæg version 1.1
 
Freezer Fiesta
Freezer FiestaFreezer Fiesta
Freezer Fiesta
 
WEEE Management Policy Update from Thailand
WEEE Management Policy Update from ThailandWEEE Management Policy Update from Thailand
WEEE Management Policy Update from Thailand
 
Electrical technician
Electrical technicianElectrical technician
Electrical technician
 
Curriculum vitae
Curriculum vitaeCurriculum vitae
Curriculum vitae
 
Computadora personal
Computadora personal Computadora personal
Computadora personal
 
En quran trans (sahih international).sahih
En quran trans (sahih international).sahihEn quran trans (sahih international).sahih
En quran trans (sahih international).sahih
 
case study-ppt-2
case study-ppt-2case study-ppt-2
case study-ppt-2
 
pointeur laser vert puissant 200mw Laser 303
pointeur laser vert puissant 200mw Laser 303pointeur laser vert puissant 200mw Laser 303
pointeur laser vert puissant 200mw Laser 303
 
Роман Гуляк "SMALL THINGS THAT MATTER"
Роман Гуляк "SMALL THINGS THAT MATTER"Роман Гуляк "SMALL THINGS THAT MATTER"
Роман Гуляк "SMALL THINGS THAT MATTER"
 
social media analytics
social media analyticssocial media analytics
social media analytics
 
Positive Change in Falls Park
Positive Change in Falls ParkPositive Change in Falls Park
Positive Change in Falls Park
 
2015 16combinepdf
2015 16combinepdf2015 16combinepdf
2015 16combinepdf
 
Marva play august 27 2015
Marva play august 27 2015Marva play august 27 2015
Marva play august 27 2015
 
laser bleu 1000mw puissant à forte vente pas cher
laser bleu 1000mw puissant à forte vente pas cherlaser bleu 1000mw puissant à forte vente pas cher
laser bleu 1000mw puissant à forte vente pas cher
 
Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4
 
Kaizen Mini Habits by Nataliya Trenina for IT Weekend
Kaizen Mini Habits by Nataliya Trenina for IT WeekendKaizen Mini Habits by Nataliya Trenina for IT Weekend
Kaizen Mini Habits by Nataliya Trenina for IT Weekend
 

Ähnlich wie Rxandroid

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
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
 
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
 
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
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx javaCongTrung Vnit
 
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
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on AndroidGuilherme Branco
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no AndroidGuilherme Branco
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalSidereo
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programmingAraf Karsh Hamid
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Richard Langlois P. Eng.
 

Ähnlich wie Rxandroid (20)

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
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
 
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
 
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
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
 
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
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Kürzlich hochgeladen (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Rxandroid

  • 1. Introduce RxJava and Android Author: Đới Thanh Thịnh Savvycom-software
  • 2. Introduction 1. Developing a complex Android app that has lots of network connections, user interactions, and animations often means writing code that is full of nested callbacks. 2. Sometimes called callback hell, is not only lengthy and hard to understand, hard to maintain. 3. ReactiveX offers an alternative approach that is both clear and concise, to manage asynchronous tasks and events.
  • 3. Overview  1. What is ReactiveX?  2. Observables, Observers  3. Operator  4. Schedulers  5. Retrofit with RxAndroid
  • 4. What is ReactiveX?  ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.  RxJava, which is a port of the Reactive Extensions library from .NET, enables Android apps to be built in this style.
  • 5. Async programming  Nowadays programming in an imperative single threaded way usually leads to strange behaviors, blocking non responsive UIs and therefore a bad user experience.  This can be avoided by handling unpredicted things asynchronously. For example actively waiting for a database query or a webservice call can cause an application freeze, if the network is not responsive.
  • 6. Async programming public List<Todo> getTodos() { List<Todo> todosFromWeb = // query a webservice (with bad network latency) return todosFromDb; } public void getTodos(Consumer<List<Todo>> todosConsumer) { Thread thread = new Thread(()-> { List<Todo> todosFromWeb = // query a webservice todosConsumer.accept(todosFromWeb); }); thread.start(); }
  • 7. Setup Setup your app/build.gradle: dependencies { compile 'io.reactivex:rxandroid:1.2.0' compile 'io.reactivex:rxjava:1.1.4' }
  • 8. Observables, Observers and Subscriptions 1. Observables  Emit items (Objects, Strings, Integers etc.).  Does not start emitting till someone subscribes. 2. Observers  To watch Observables by subscribing to them and consumes data 3. Manipulation operators (this is the “functional programming” part)  Transforms  Filters  Etc.  The observable we just created will emit its data only when it has at least one observer.  Similar to the observer pattern. Except, doesn’t start emitting till there is a subscriber.
  • 9. Creating Observable  RxJava provides several methods to create an observable.  Observable.just() - Allows to create an observable as wrapper around other data types  Observable.from() - takes a collection or an array and emits their values in their order in the data structure  Observable.fromCallable() - Allows to create an observable for a Callable`  To create observers:  Implement Action1 - Allow you to create a simple observer which has a call methods. This method is called if a new object is emitted.
  • 10. Defining Observables // Observables emit any number of items to be processed // The type of the item to be processed needs to be specified as a "generic type" // In this case, the item type is `String` Observable<String> myObservable = Observable.create( new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> sub) { // "Emit" any data to the subscriber sub.onNext("a"); sub.onNext("b"); sub.onNext("c"); // Trigger the completion of the event sub.onCompleted(); } } ); This observable event emits the data “a”, “b”, “c” and then completes.
  • 11. Defining Observers Observer<String> mySubscriber = new Observer<String>() { // Triggered for each emitted value @Override public void onNext(String s) { System.out.println("onNext: " + s); } // Triggered once the observable is complete @Override public void onCompleted() { System.out.println("done!"); } // Triggered if there is any errors during the event @Override public void onError(Throwable e) { } }; Now let’s create a Observer to consume this emitted data from the Observable:
  • 12. Subscribing to Observables  An Observer can be attached to an Observable in order to respond to emitted data with: • // Attaches the subscriber above to the observable object • myObservable.subscribe(mySubscriber); Outputs: // onNext: "a" // onNext: "b" // onNext: "c" // done! Observable Observers
  • 13. Subscribing to Observables  void onNext(T t):  Provides the Observer with a new item to observe.  may call this method 0 or more times.  will not call this method again after it calls either onCompleted or onError  void onCompleted():  Notifies the Observer that the Observable has finished sending push-based notifications.  void onError(Throwable e): Notifies the Observer that the Observable has experienced an error condition.  Subscription subscribe(final Observer<? super T> observer):  Subscribes to an Observable and provides an Observer that implements functions to handle the items the Observable emits and any error or completion
  • 14. Operator  Just — convert an object or a set of objects into an Observable that emits that or those objects Observable.just(1, 2, 3).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Complete!"); } @Override public void onError(Throwable e) { } @Override public void onNext(Integer integer) { System.out.println("onNext!"); } }); System.out: onNext!: 1 System.out: onNext!: 2 System.out: onNext!: 3 System.out: Complete!
  • 15. Operator  From — Converts an Array into an Observable that emits the items in the Array. Integer[] items = {0, 1, 2, 3, 4}; Observable.from(items).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Complete!"); } @Override public void onError(Throwable e) { } @Override public void onNext(Integer integer) { System.out.println("onNext from!" + integer); } }); System.out: onNext!0 System.out: onNext!1 System.out: onNext!2 System.out: onNext!3 System.out: onNext!4 System.out: Complete!
  • 16. Operator  Filter : Filters items emitted by an Observable by only emitting those that satisfy a specified predicate. Observable.just(1, 2, 3, 4, 5) .filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return integer < 4; } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Complete!"); } @Override public void onError(Throwable e) { System.out.println("onError!"); } @Override public void onNext(Integer integer) { System.out.println("onNext just!" + integer); } }); System.out: onNext!0 System.out: onNext!1 System.out: onNext!2 System.out: onNext!3 System.out: Complete!
  • 17. Operator  Map: Transform the items emitted by an Observable by applying a function to each item Observable.just(1, 2, 3, 4, 5) .map(new Func1<Integer, Integer>() { @Override public Integer call(Integer integer) { return integer * 10; } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Complete!"); } @Override public void onError(Throwable e) { System.out.println("onError!"); } @Override public void onNext(Integer integer) { System.out.println("onNext!" + integer); } }); System.out: onNext! 10 System.out: onNext! 20 System.out: onNext! 30 System.out: onNext! 40 System.out: onNext! 50 System.out: Complete!
  • 18. Operator – Many Others  http://reactivex.io/documentation/operators.html  Operators By Category  Creating Observables: Create, Just …  Transforming Observables: Map, FlatMap, …  Filtering Observables: First , Filter , …  Combining Observables: Join , Merge ,…  Error Handling Operators: Catch , Retry  Observable Utility Operators:Subscribe, SubscribeOn  Conditional and Boolean Operators:Contains, …  Mathematical and Aggregate Operators:Average, Count
  • 19. Schedulers  RxJava is synchronous by default, but work can be defined asynchronously using schedulers. For instance, we can define that the network call should be done on a background thread, but the callback should be done on the main UI thread. Observable.from(doLongNetwork()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getObserver()) 1. Observable 2.Schedulers 3. Observer
  • 20. Schedulers These schedulers than then be used to control which thread an observable or the subscriber are operating on using the subscribeOn() and observeOn()
  • 21. Schedulers  subscribeOn(): Basic rules of rxjava threading: 1. rxjava is single threaded by default 2. subscribeOn only affects upstream 3. only the subscribeOn closest to the source matters 4. observeOn only affects downstream
  • 22. Schedulers 1. rxjava is single threaded by default When you do not use observeOn, subscribeOn, or an operator that runs on a particular scheduler , the callback will be receieved on the thread subscribe happened on. 2. subscribeOn only affects upstream getANumberObservable() .subscribeOn(Schedulers.io()) .map(new Func1<Integer, String>() { @Override public String call(Integer integer) { Log.i("Operator thread", Thread.currentThread().getName()); return String.valueOf(integer); } }) .subscribe(new Action1<String>() { @Override public void call(String s) { Log.i("Subscriber thread", Thread.currentThread().getName() + " onNext: " + s); } }); Output: Observable thread: RxIoScheduler-2 Operator thread: RxIoScheduler-2 Subscriber thread: RxIoScheduler-2 onNext: 1
  • 23. Schedulers 3. Only the subscribeOn closest to the source matters: Observable.just("Some String") .map(new Func1<String, Integer>() { @Override public Integer call(String s) { return s.length(); } }) .subscribeOn(Schedulers.computation()) // changing to computation .subscribeOn(Schedulers.io()) // won’t change the thread to IO .subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer integer) { System.out.println("onNext!" + integer); Log.d("onNext", "Number " + integer + " Thread: " + Thread.currentThread().getName()); } }); Output System.out: onNext!11 onNext: Number 11 Thread: RxComputationScheduler-1
  • 24. Schedulers 4. observeOn only affects downstream ObserveOn function () pass an argument is a Scheduler will make the Operator and Subscriber called behind it is running on thread provided by this Scheduler.
  • 25. observeOn getANumberObservable() //.subscribeOn(Schedulers.io()) .observeOn(Schedulers.newThread()) .map(new Func1<Integer, String>() { @Override public String call(Integer integer) { Log.i("Operator thread", Thread.currentThread().getName()); return String.valueOf(integer); } }) .subscribe(new Action1<String>() { @Override public void call(String s) { Log.i("Subscriber thread", Thread.currentThread().getName() + " onNext: " + s); } }); Output Observable thread: main Operator thread: RxNewThreadScheduler-1 Subscriber thread: RxNewThreadScheduler- 1 onNext: 1
  • 26. Deferring Observable Create(…): actually creates Observable immediately. public final static <T> Observable<T> create(OnSubscribe<T> f) { return new Observable<T>(hook.onCreate(f)); } Defer(…): creates Observable only when subscriber subscribes, create a new Observable each time you get a subscriber. public final static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) { return create(new OnSubscribeDefer<T>(observableFactory)); }
  • 27. Deferring Observable SomeType instance = new SomeType(); Observable<String> value = instance.valueObservable(); instance.setValue("Some Value"); value.subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { Log.d("Thinhdt", "Defer Observable: " + s); } }); Output: Thinhdt: Defer Observable: null
  • 28. Deferring Observable : Solution public Observable<String> valueObservable() { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext(value); subscriber.onCompleted(); } }); } Observable.cr eate() public Observable<String> valueObservable() { return Observable.defer(new Func0<Observable<String>>() { @Override public Observable<String> call() { return Observable.just(value); } }); } Observable. defer
  • 29. Replacing AsyncTask with Observables // This constructs an `Observable` to download the image public Observable<Bitmap> getImageNetworkCall() { // Insert network call here! } // Construct the observable and use `subscribeOn` and `observeOn` // This controls which threads are used for processing and observing Subscription subscription = getImageNetworkCall() // Specify the `Scheduler` on which an Observable will operate .subscribeOn(Schedulers.io()) // Specify the `Scheduler` on which a subscriber will observe this `Observable` .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Bitmap>() { // This replaces `onPostExecute(Bitmap bitmap)` @Override public void onNext(Bitmap bitmap) { // Handle result of network request } @Override public void onCompleted() { // Update user interface if needed } @Override public void onError() { // Update user interface to handle error } }); 1. Thread to perform the task in the background used subscribeOn() 2. To update UI on main thread used observeOn()
  • 30. Retrofit with RxAndroid 1. public interface MyApiEndpointInterface { @GET("/users/{username}") Observable<User> getUser(@Path("username") String username); } 2. MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class); // Get the observable User object Observable<User> call = apiService.getUser(username); // To define where the work is done, we can use `observeOn()` with Retrofit // This means the result is handed to the subscriber on the main thread call.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<User>() { @Override public void onNext(User user) { // Called once the `User` object is available } @Override public void onCompleted() { // Nothing to do here } @Override public void onError(Throwable e) { // cast to retrofit.HttpException to get the response code if (e instanceof HttpException) { HttpException response; int code = response.code(); } } });
  • 31. Resources:  https://hackmd.io/s/BkITYDZf  http://www.slideshare.net/penano/rx-javasc  http://reactivex.io  http://www.vogella.com/tutorials/RxJava/article.html  http://randomdotnext.com/retrofit-rxjava/  http://blog.danlew.net/2015/07/23/deferring-observable-code- until-subscription-in-rxjava/  https://github.com/ruler88/GithubDemo https://github.com/thinhdt/DemoRxAndroid/ https://github.com/thinhdt/Retrofit-RxAndroid

Hinweis der Redaktion

  1. http://www.vogella.com/tutorials/RxJava/article.html
  2. This observable event emits the data “a”, “b”, “c” and then completes.
  3. These schedulers than then be used to control which thread an observable or the subscriber are operating on using the subscribeOn() and observeOn()
  4. subscribeOn() instructs the source Observable which thread to emit items on
  5. It is helpful to instruct a source Observable which Scheduler to use via subscribeOn(), and the source Observable will emit items on one of that Scheduler's threads
  6. Bạn cần lưu ý điều này khi sử dụng các hàm như Observable.just(), Observable.from() hay Observable.range(): Những hàm này sẽ nhận vào giá trị ngay khi chúng được khởi tạo nên subscribeOn() sẽ không có tác dụng; Nguyên nhân là do subscribeOn() chỉ có tác dụng khi hàm subscribe() được gọi đến, mà những hàm khởi tạo nói trên lại khởi tạo Observable trước khi gọi subscriber() nên các bạn cần tránh đưa vào các giá trị mà cần tính toán trong 1 khoảng thời gian dài (blocking) vào các hàm khởi tạo đó. Thay vào đó đối với các hàm blocking thì bạn có thể sử dụng Observable.create() hoặc Observable.defer(). 2 hàm này về cơ bản sẽ đảm bảo là Observable sẽ chỉ được khởi tạo khi hàm subscribe() được gọi đến.
  7. The only downside to defer() is that it creates a new Observable each time you get a subscriber. create() can use the same function for each subscriber, so it's more efficient. As always, measure performance and optimize if necessary.
  8. http://stackoverflow.com/questions/34054452/rxandroid-create-simple-hot-observable