SlideShare a Scribd company logo
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

More Related Content

Viewers also liked

Curriculum vitae
Curriculum vitaeCurriculum vitae
Curriculum vitae
erika3105
 
Computadora personal
Computadora personal Computadora personal
Computadora personal
Trinidad Giraudo
 
En quran trans (sahih international).sahih
En quran trans (sahih international).sahihEn quran trans (sahih international).sahih
En quran trans (sahih international).sahih
Abu Qasim
 
case study-ppt-2
case study-ppt-2case study-ppt-2
case study-ppt-2
Neha 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 303
hannahjanelle
 
Роман Гуляк "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 analytics
Neha Kumari
 
Positive Change in Falls Park
Positive Change in Falls ParkPositive Change in Falls Park
Positive Change in Falls Park
Keep Thailand Beautiful
 
2015 16combinepdf
2015 16combinepdf2015 16combinepdf
2015 16combinepdf
madhesi
 
Marva play august 27 2015
Marva play august 27 2015Marva play august 27 2015
Marva play august 27 2015
Marva 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 cher
hannahjanelle
 
Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4Heartfulness Magazine Issue 4
Heartfulness Magazine Issue 4
heartfulness
 
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
Agile Ukraine
 
Boiling and vaporization and freezing
Boiling and vaporization and freezingBoiling and vaporization and freezing
Boiling and vaporization and freezing
Prathamcbh
 
Niladri Debnath__opt
Niladri Debnath__optNiladri Debnath__opt
Niladri Debnath__opt
Niladri Debnath
 
En the beautiful names of allah
En the beautiful names of allahEn the beautiful names of allah
En the beautiful names of allah
Abu Qasim
 

Viewers also liked (16)

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
 
Boiling and vaporization and freezing
Boiling and vaporization and freezingBoiling and vaporization and freezing
Boiling and vaporization and freezing
 
Niladri Debnath__opt
Niladri Debnath__optNiladri Debnath__opt
Niladri Debnath__opt
 
En the beautiful names of allah
En the beautiful names of allahEn the beautiful names of allah
En the beautiful names of allah
 

Similar to Rxandroid

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
YarikS
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
Shahar Barsheshet
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
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
harintrivedi
 
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
Netesh 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 2
JollyRogers5
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
CongTrung Vnit
 
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
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
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
Fernando Cejas
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
Guilherme Branco
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
Guilherme Branco
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
Designveloper
 
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
Sidereo
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
Araf 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 5
Richard Langlois P. Eng.
 

Similar to 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
 

Recently uploaded

Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
IsmaelVazquez38
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
سمير بسيوني
 
How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17
Celine George
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
ImMuslim
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
blueshagoo1
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 

Recently uploaded (20)

Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
 
How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17
 
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 

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

Editor's Notes

  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