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?

Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word javaRavi Purohit
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User GroupTamir Dresher
 
Be smart when testing your Akka code
Be smart when testing your Akka codeBe smart when testing your Akka code
Be smart when testing your Akka codeMykhailo Kotsur
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJavaSanjay Acharya
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityDmytro Patserkovskyi
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry Voloshko
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitExploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitSylvain Hellegouarch
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
Building responsive application with Rx - confoo - tamir dresher
Building responsive application with Rx - confoo - tamir dresherBuilding responsive application with Rx - confoo - tamir dresher
Building responsive application with Rx - confoo - tamir dresherTamir Dresher
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talkrahulrevo
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In JavaKohei Nozaki
 

Was ist angesagt? (20)

Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word java
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
 
Be smart when testing your Akka code
Be smart when testing your Akka codeBe smart when testing your Akka code
Be smart when testing your Akka code
 
Akka Testkit Patterns
Akka Testkit PatternsAkka Testkit Patterns
Akka Testkit Patterns
 
Architecture
ArchitectureArchitecture
Architecture
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitExploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
 
Posfix
PosfixPosfix
Posfix
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
Building responsive application with Rx - confoo - tamir dresher
Building responsive application with Rx - confoo - tamir dresherBuilding responsive application with Rx - confoo - tamir dresher
Building responsive application with Rx - confoo - tamir dresher
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In Java
 

Andere mochten auch

RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리
RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리
RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리Soyeon Kim
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
React.js and Flux in details
React.js and Flux in detailsReact.js and Flux in details
React.js and Flux in detailsArtyom Trityak
 
Android Design Principles and Popular Patterns
Android Design Principles and Popular PatternsAndroid Design Principles and Popular Patterns
Android Design Principles and Popular PatternsFaiz Malkani
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/FluxKeuller Magalhães
 
Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1Damian Legawiec
 
Clean architecture on android
Clean architecture on androidClean architecture on android
Clean architecture on androidBenjamin Cheng
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroidHiroyuki Kusu
 
Lightning Talk - Clean Architecture and Design
Lightning Talk - Clean Architecture and DesignLightning Talk - Clean Architecture and Design
Lightning Talk - Clean Architecture and DesignDeivison Sporteman
 
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming waynejo
 
Is Activity God? ~ The MVP Architecture ~
Is Activity God? ~ The MVP Architecture ~Is Activity God? ~ The MVP Architecture ~
Is Activity God? ~ The MVP Architecture ~Ken William
 
Clean architecture: Android
Clean architecture: AndroidClean architecture: Android
Clean architecture: Androidintive
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMMudasir Qazi
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean ArchitectureBadoo
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean ArchitectureRoc Boronat
 

Andere mochten auch (20)

RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리
RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리
RxAndroid: 비동기 및 이벤트 기반 프로그래밍을 위한 라이브러리
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Choice Paralysis
Choice ParalysisChoice Paralysis
Choice Paralysis
 
About Flux
About FluxAbout Flux
About Flux
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
React.js and Flux in details
React.js and Flux in detailsReact.js and Flux in details
React.js and Flux in details
 
Android Design Principles and Popular Patterns
Android Design Principles and Popular PatternsAndroid Design Principles and Popular Patterns
Android Design Principles and Popular Patterns
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/Flux
 
Flux architecture
Flux architectureFlux architecture
Flux architecture
 
React & Flux Workshop
React & Flux WorkshopReact & Flux Workshop
React & Flux Workshop
 
Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1Intro to Flux - ReactJS Warsaw #1
Intro to Flux - ReactJS Warsaw #1
 
Clean architecture on android
Clean architecture on androidClean architecture on android
Clean architecture on android
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
 
Lightning Talk - Clean Architecture and Design
Lightning Talk - Clean Architecture and DesignLightning Talk - Clean Architecture and Design
Lightning Talk - Clean Architecture and Design
 
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming GDG 2014 - RxJava를 활용한 Functional Reactive Programming
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
 
Is Activity God? ~ The MVP Architecture ~
Is Activity God? ~ The MVP Architecture ~Is Activity God? ~ The MVP Architecture ~
Is Activity God? ~ The MVP Architecture ~
 
Clean architecture: Android
Clean architecture: AndroidClean architecture: Android
Clean architecture: Android
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean Architecture
 

Ähnlich wie RxAndroid

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
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 java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
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.
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSara Torkey
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsJeff Smith
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsJeff Smith
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsJeff Smith
 

Ähnlich wie RxAndroid (20)

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 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 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
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
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
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and Solutions
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and Solutions
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and Solutions
 

Kürzlich hochgeladen

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
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
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 

Kürzlich hochgeladen (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
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
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 

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