SlideShare a Scribd company logo
1 of 24
Download to read offline
A Few
Words
About
RXJAVA
@Saiimons
I’m Simon Guerout.
C#O at Sidereo

s@sidereo.com

@saiimons

@sidereomobile

http://sidereo.com
Created by Microsoft for .NET
Functional Reactive Programming
Now available for Java and Android
So, What’s Rx
Reactive extensions are a framework created by Microsoft for .NET at the end of 2009.

It is a «library that allows programmers to write succinct declarative code to orchestrate and coordinate asynchronous and event-based programs »

The way you write code with this library might be referred to as functional reactive programming, we’ll talk more about this during the presentation.

It is now available for Java and Android. The specifics for Android are helpers for thread and UI stuff.

Jake Wharton is a huge contributor for the Android version.
Black boxes, input, output
Streams, streams, streams
Observer pattern
Functional Reactive Programming
Think of functional programming as developing a stateless application.

You are writing black boxes, taking input data, processing it and delivery the output result.

Using this way of thinking, you have to put your mind in « stream mode » : everything is a stream.

Wether the user clicks a button, an API responds to a request or the GPS coordinate changes.

In the real world, Reactive extensions rely on an extended version of the Observer pattern.

This pattern is a pretty basic way off expressing the callback mechanism on an object.
1
Key Concepts
You have to learn these
Let me first introduce you to key concepts, which you have to know about if you want to start using Rx.
These, you will use :
Observable<SomeType>, the guy who emits the data.
Observer<SomeType>, the guy who listens to the data.
Classes And Methods
In order to use the framework, you must be aware that you will handle mainly 2 types :

The Observable, which is the implementation of the pattern, it is used to subscribe to the data output.

The Observer, which will be called when 

• new data is available

• the end of the stream was reached

• an error occurred
public interface Observer<T> {
void onCompleted();
void onError(Throwable e);
void onNext(T t);
}
public abstract class Subscriber<T>
implements Observer<T>, Subscription { … }
Inside The Observer
When creating an observer, you will have to write 3 functions :

• onNext, which will be called when new data is available from the Observable, this is where you can process the new data.

• onCompleted, when no more data will be delivered from the Observable, this is where you can free some resources.

• onError, which will be called when something failed.

Mainly, you will extend the Subscriber class, it is handy, and it supports subscription (which will be covered later)
public final static <T> Observable<T>
from(T[] array)
public final static <T> Observable<T>
create(OnSubscribe<T> f)
Inside The Observable
There are basically 2 ways to start creating an Observable :

• Either you can set the list of values to be emitted directly.

• Or you can implement the OnSubscribe interface : 

• your implementation will be called each time a new subscriber wants your data,

• you are responsible for calling onNext, onCompleted and onError when needed

This second case is very handy to wrap some calculation, and also work with a subscription.
Subscription
public interface Subscription {
void unsubscribe();
boolean isUnsubscribed();
}
public abstract class Subscriber<T>
implements Observer<T>, Subscription {
public final void add(Subscription s){ … }
}
The subscription is another essential part of Rx : it handles the fact that sometimes, you might want to stop listening to an observable.

It is a very handy interface, and works with a whole chain of calls (ie. if you have built a chain of observables, you only need to unsubscribe your own subscriber).

Another use for this interface, is when you are creating your own observable.

You can query the subscriber in order to know wether it is still active.

If you add a subscription to a subscriber, you will be notified asynchronously when this subscriber unsubscribes.
Map
Filter
Cast
Merge
…

http://rxmarbles.com/

Operators
In order to finish introducing the key concepts, I’ll have to talk about the Operators.

The operators are a set of tools allowing you to perform operations on the data emitted by an Observable.

There already is a set of very handy functions available with the framework, I will not cover each of the operator, but here are a few examples :

GO TO rxmarbles.com
Sum Up
In order to sum up the concepts : 

• An observable emits data of a kind

• You can apply transformations on any observable

• You can subscribe (and unsubscribe) to any observable

• 3 main events : onNext, onCompleted, onError
2
Android + Rx
Some added sorcery
RxAndroid
compile 'io.reactivex:rxandroid:1.0.1'

compile 'io.reactivex:rxjava:1.0.14'

RxLifecycle
compile 'com.trello:rxlifecycle:0.3.0'

compile 'com.trello:rxlifecycle-components:0.3.0'
Libraries
There are basically 3 sets of libraries designed for Android.

RxAndroid : This module offers the integration of a few helpers, which are basically making it possible to run code in the Main thread or a Handler Thread.

RxLifecycle : This module gives you handy wrappers to handle the specificity of Activities, Fragments, …
RxBinding-*

compile 'com.jakewharton.rxbinding:rxbinding:0.2.0'

compile 'com.jakewharton.rxbinding:rxbinding-support-v4:0.2.0'

compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.2.0'

compile 'com.jakewharton.rxbinding:rxbinding-design:0.2.0'

compile 'com.jakewharton.rxbinding:rxbinding-recyclerview-v7:0.2.0'

Libraries
RxBindings
This set of module is developed by Jake Wharton, and will offer a lot of basic features you would not want to write by yourself.

Basically this covers any callback system used in the UI.

For example, you can get the observable for the click events of any view.
Main thread vs . background threads is a recurrent issue.
AsyncTask or any similar API become heavily used.
Main thread, is the king, you end up « posting » a lot.
Observable
public final Observable<T> observeOn(Scheduler scheduler);
public final Observable<T> subscribeOn(Scheduler scheduler);
AndroidSchedulers
public static Scheduler mainThread();
Threads
One particularity of the Android system, is that many operations have to run in the Main (UI) thread.

As RxJava was built for a multithreaded environments, it is easy to overcome this, using :

• observeOn when you need the result to happen in a specific thread

• subscribeOn when you need to processing to happen in a specific thread

RxAndroid provides methods which will return a scheduler for the main thread (or for handler threads when needed).
Memory leaks are bad.
Calling UI outside the main thread is bad.
Calling code when you Activity was destroyed is bad.
public class MyActivity extends RxActivity {
@Override
public void onResume() {
super.onResume();
myObservable
.compose(bindToLifecycle())
.subscribe();
}
}
Lifecycle
Using the Lifecycle components, you can extend Activity or AppCompatActivity, in order to be able to bind to a specific part of lifecycle.

For example : resume / pause, create / destroy.

Note that you will have to face weird casts on the compose depending on the data you observe.
3
Real Life Example
‘Cause it’s always better to use it for real…
Let’s move on to a real world example, which will offer you a vision on how to use Rx and its extensions.
Location, Location, Location…
Let’s imagine you want to be able to listen to location changes from your application.

Let’s say, your user can activate or reactive location, and change the rate at which location is updated.

Let’s say you want your UI to be updated, and a database of the positions to be be populated.

(which would be a very common case for a fitness app)

If you were to make such a UI / app, which emitted data would you consider using ?
GoogleApiClient : you will need it for using the FusedLocationApi
LocationRequest : this guy tells the FusedLocationApi which kind of location will be
helpful for you.
Clicks : to the user’s command you will listen, young padawan.

Players
This game has 3 players :

• You need to set up a GoogleApiClient, and get it "connected" only when you need to listen to locations. This class is giving you access to a set of APIs controlled by
the Google Play Services. It needs to be initialized in a separate thread, let’s spare us some pain, and create an Observable.

• You will then have a few parameters to give to the LocationServicesApi : these are LocationRequests. They will change as your user selects one of the options
available, so we might have an observable for this too.

• Your user will use a few buttons, which will be emitting events, we may need to convert.

=> Have a look a the code
What Did We Learn ?
Observables can be Hot or Cold, which roughly translates to active or passive.
Operators will help you transform emitted values.
Use Subscriptions it helps you avoiding mess.
Observables can be emitted it may save you time and complexity.
Android has its own extensions, use them!
First, please do not take this example as the perfect source.

It is merely an example, and I made some voluntarily specific uses of RX, so that you can see how many problems can be adressed.

The first thing I’d like to underline is the fact that the Observables can be Hot or Cold.

A Cold Observable is for example the Google Api Client one : it will only give a new GAC if you subscribe to it.

A Hot Observable is for example the View Click one : clicks will happen, wether there is a subscriber or not.

Subscriptions are the best tool when it comes to handling the lifecycle of your objects.

Use them, you will avoid memory leaks, and other bugs.

Emitted values can be transformed easily through black boxes se how I managed to get a Location Request from a ViewClickEvent.

This transformed value is then emitted to the next item in the chain.

Observables can be emitted : this is a tough one, but can be very helpful. 

For example, we get many LocationObservables, and use the switch operator to select the latest one.

This helps wrapping up some APIs which are not letting you update their settings (or avoiding adding weird methods to do this).

I have used some of the awesome Android extensions for RxJava : Listeners for the view, Lifecycle sanity, …

USE THEM : you will save a lot of time, and a lot of boilerplate code.
Clone
https://github.com/saiimons/RxLocationTutorial
I’ll let you guys checkout the code of this little demonstration
Synthetic code
Functional slices of code
Android specifics
Reusable components
Replaceable blocks

Advantages / Drawbacks
Learning curve
Readability
Debugging

Advantages :

• If you like your code in synthetic, functional blocks, you will like Rx

• It has libraries helping you integrating with Android : USE THEM

• Your components can be reused / replaced : for testing or for evolutions of your app

Drawbacks :

• It can be painful to learn and discover all the Observable methods

• A neophyte will find it hard to understand (though you should definitely write documentation)

• Debugging can be a little bit tricky, because of some lengthy stack traces
Observable<Question> questions = Observable.create(people);
questions.subscribe(
new Action1<Question>() {
@Override
public void call(Question question) {
Simon.answer(question);
}
}
);
Questions
If you have any questions, now is the time !
Thank You!
Share if you liked this deck!
@Saiimons

More Related Content

What's hot

Analytics tools and Instruments
Analytics tools and InstrumentsAnalytics tools and Instruments
Analytics tools and Instruments
Krunal Soni
 
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
Daniel Katz
 

What's hot (11)

Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
Technologies used in the PVS-Studio code analyzer for finding bugs and potent...
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
 
Analytics tools and Instruments
Analytics tools and InstrumentsAnalytics tools and Instruments
Analytics tools and Instruments
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
ICPSR - Complex Systems Models in the Social Sciences - Lab Session 6 - Profe...
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Ansible at FOSDEM (Ansible Dublin, 2016)
Ansible at FOSDEM (Ansible Dublin, 2016)Ansible at FOSDEM (Ansible Dublin, 2016)
Ansible at FOSDEM (Ansible Dublin, 2016)
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Cucumber presentation
Cucumber presentationCucumber presentation
Cucumber presentation
 
Romero Blueprint Compendium
Romero Blueprint CompendiumRomero Blueprint Compendium
Romero Blueprint Compendium
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 

Viewers also liked

RiverWatch Weekly Newsletter 7-2016
RiverWatch Weekly Newsletter 7-2016RiverWatch Weekly Newsletter 7-2016
RiverWatch Weekly Newsletter 7-2016
Shane Payne
 
одуванчики Галушко
одуванчики Галушкоодуванчики Галушко
одуванчики Галушко
ozimovska
 
งานนำเสนอ1 วิชา IS
งานนำเสนอ1 วิชา ISงานนำเสนอ1 วิชา IS
งานนำเสนอ1 วิชา IS
Kanyapak Thongsuk
 
Thoracic organs and vessels
Thoracic organs and vesselsThoracic organs and vessels
Thoracic organs and vessels
Jamie Desilva
 
Areas of housekeeping department responsbilities
Areas of housekeeping department responsbilitiesAreas of housekeeping department responsbilities
Areas of housekeeping department responsbilities
Shahira Karim
 
операційні системи
операційні системиопераційні системи
операційні системи
anonim555
 
הרצאה ממים
הרצאה ממיםהרצאה ממים
הרצאה ממים
sarit cohen
 

Viewers also liked (18)

Tugas politik_transaksional_di_lembaga_legislatif
Tugas  politik_transaksional_di_lembaga_legislatifTugas  politik_transaksional_di_lembaga_legislatif
Tugas politik_transaksional_di_lembaga_legislatif
 
Coussins2
Coussins2Coussins2
Coussins2
 
Ot
OtOt
Ot
 
Spice Tour
Spice TourSpice Tour
Spice Tour
 
RiverWatch Weekly Newsletter 7-2016
RiverWatch Weekly Newsletter 7-2016RiverWatch Weekly Newsletter 7-2016
RiverWatch Weekly Newsletter 7-2016
 
OTA : Mettre à jour un device Android, ok mais comment ça marche ?
OTA : Mettre à jour un device Android, ok mais comment ça marche ? OTA : Mettre à jour un device Android, ok mais comment ça marche ?
OTA : Mettre à jour un device Android, ok mais comment ça marche ?
 
Phan tich bop dh28kt03 nhom xuka
Phan tich bop dh28kt03 nhom xukaPhan tich bop dh28kt03 nhom xuka
Phan tich bop dh28kt03 nhom xuka
 
カタカナの練習
カタカナの練習カタカナの練習
カタカナの練習
 
одуванчики Галушко
одуванчики Галушкоодуванчики Галушко
одуванчики Галушко
 
งานนำเสนอ1 วิชา IS
งานนำเสนอ1 วิชา ISงานนำเสนอ1 วิชา IS
งานนำเสนอ1 วิชา IS
 
Thoracic organs and vessels
Thoracic organs and vesselsThoracic organs and vessels
Thoracic organs and vessels
 
Online Shopping Cart
Online Shopping CartOnline Shopping Cart
Online Shopping Cart
 
Is hearing loss be an indicator of loss of cognitive abilities
Is hearing loss be an indicator of loss of cognitive abilities Is hearing loss be an indicator of loss of cognitive abilities
Is hearing loss be an indicator of loss of cognitive abilities
 
Dever
DeverDever
Dever
 
Areas of housekeeping department responsbilities
Areas of housekeeping department responsbilitiesAreas of housekeeping department responsbilities
Areas of housekeeping department responsbilities
 
операційні системи
операційні системиопераційні системи
операційні системи
 
Google 3rd party brand hotels
Google 3rd party brand hotelsGoogle 3rd party brand hotels
Google 3rd party brand hotels
 
הרצאה ממים
הרצאה ממיםהרצאה ממים
הרצאה ממים
 

Similar to RxJava pour Android : présentation lors du GDG Android Montréal

Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
Katy Allen
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
Nicole Gomez
 

Similar to RxJava pour Android : présentation lors du GDG Android Montréal (20)

Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Rx Swift
Rx SwiftRx Swift
Rx Swift
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...
 
Sdlc
SdlcSdlc
Sdlc
 
Sdlc
SdlcSdlc
Sdlc
 
An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)An Introduction to Prometheus (GrafanaCon 2016)
An Introduction to Prometheus (GrafanaCon 2016)
 
DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Combine in iOS - Basics
Combine in iOS - BasicsCombine in iOS - Basics
Combine in iOS - Basics
 
Reactotron - A Debugging Agent
Reactotron -  A Debugging AgentReactotron -  A Debugging Agent
Reactotron - A Debugging Agent
 
Android
AndroidAndroid
Android
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
 
Microservices and Prometheus (Microservices NYC 2016)
Microservices and Prometheus (Microservices NYC 2016)Microservices and Prometheus (Microservices NYC 2016)
Microservices and Prometheus (Microservices NYC 2016)
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
 
香港六合彩
香港六合彩香港六合彩
香港六合彩
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
anilsa9823
 

Recently uploaded (7)

Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 

RxJava pour Android : présentation lors du GDG Android Montréal

  • 2. I’m Simon Guerout. C#O at Sidereo s@sidereo.com @saiimons @sidereomobile http://sidereo.com
  • 3. Created by Microsoft for .NET Functional Reactive Programming Now available for Java and Android So, What’s Rx Reactive extensions are a framework created by Microsoft for .NET at the end of 2009. It is a «library that allows programmers to write succinct declarative code to orchestrate and coordinate asynchronous and event-based programs » The way you write code with this library might be referred to as functional reactive programming, we’ll talk more about this during the presentation. It is now available for Java and Android. The specifics for Android are helpers for thread and UI stuff. Jake Wharton is a huge contributor for the Android version.
  • 4. Black boxes, input, output Streams, streams, streams Observer pattern Functional Reactive Programming Think of functional programming as developing a stateless application. You are writing black boxes, taking input data, processing it and delivery the output result. Using this way of thinking, you have to put your mind in « stream mode » : everything is a stream. Wether the user clicks a button, an API responds to a request or the GPS coordinate changes. In the real world, Reactive extensions rely on an extended version of the Observer pattern. This pattern is a pretty basic way off expressing the callback mechanism on an object.
  • 5. 1 Key Concepts You have to learn these Let me first introduce you to key concepts, which you have to know about if you want to start using Rx.
  • 6. These, you will use : Observable<SomeType>, the guy who emits the data. Observer<SomeType>, the guy who listens to the data. Classes And Methods In order to use the framework, you must be aware that you will handle mainly 2 types : The Observable, which is the implementation of the pattern, it is used to subscribe to the data output. The Observer, which will be called when • new data is available • the end of the stream was reached • an error occurred
  • 7. public interface Observer<T> { void onCompleted(); void onError(Throwable e); void onNext(T t); } public abstract class Subscriber<T> implements Observer<T>, Subscription { … } Inside The Observer When creating an observer, you will have to write 3 functions : • onNext, which will be called when new data is available from the Observable, this is where you can process the new data. • onCompleted, when no more data will be delivered from the Observable, this is where you can free some resources. • onError, which will be called when something failed. Mainly, you will extend the Subscriber class, it is handy, and it supports subscription (which will be covered later)
  • 8. public final static <T> Observable<T> from(T[] array) public final static <T> Observable<T> create(OnSubscribe<T> f) Inside The Observable There are basically 2 ways to start creating an Observable : • Either you can set the list of values to be emitted directly. • Or you can implement the OnSubscribe interface : • your implementation will be called each time a new subscriber wants your data, • you are responsible for calling onNext, onCompleted and onError when needed This second case is very handy to wrap some calculation, and also work with a subscription.
  • 9. Subscription public interface Subscription { void unsubscribe(); boolean isUnsubscribed(); } public abstract class Subscriber<T> implements Observer<T>, Subscription { public final void add(Subscription s){ … } } The subscription is another essential part of Rx : it handles the fact that sometimes, you might want to stop listening to an observable. It is a very handy interface, and works with a whole chain of calls (ie. if you have built a chain of observables, you only need to unsubscribe your own subscriber). Another use for this interface, is when you are creating your own observable. You can query the subscriber in order to know wether it is still active. If you add a subscription to a subscriber, you will be notified asynchronously when this subscriber unsubscribes.
  • 10. Map Filter Cast Merge … http://rxmarbles.com/ Operators In order to finish introducing the key concepts, I’ll have to talk about the Operators. The operators are a set of tools allowing you to perform operations on the data emitted by an Observable. There already is a set of very handy functions available with the framework, I will not cover each of the operator, but here are a few examples : GO TO rxmarbles.com
  • 11. Sum Up In order to sum up the concepts : • An observable emits data of a kind • You can apply transformations on any observable • You can subscribe (and unsubscribe) to any observable • 3 main events : onNext, onCompleted, onError
  • 12. 2 Android + Rx Some added sorcery
  • 13. RxAndroid compile 'io.reactivex:rxandroid:1.0.1' compile 'io.reactivex:rxjava:1.0.14' RxLifecycle compile 'com.trello:rxlifecycle:0.3.0' compile 'com.trello:rxlifecycle-components:0.3.0' Libraries There are basically 3 sets of libraries designed for Android. RxAndroid : This module offers the integration of a few helpers, which are basically making it possible to run code in the Main thread or a Handler Thread. RxLifecycle : This module gives you handy wrappers to handle the specificity of Activities, Fragments, …
  • 14. RxBinding-* compile 'com.jakewharton.rxbinding:rxbinding:0.2.0' compile 'com.jakewharton.rxbinding:rxbinding-support-v4:0.2.0' compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.2.0' compile 'com.jakewharton.rxbinding:rxbinding-design:0.2.0' compile 'com.jakewharton.rxbinding:rxbinding-recyclerview-v7:0.2.0' Libraries RxBindings This set of module is developed by Jake Wharton, and will offer a lot of basic features you would not want to write by yourself. Basically this covers any callback system used in the UI. For example, you can get the observable for the click events of any view.
  • 15. Main thread vs . background threads is a recurrent issue. AsyncTask or any similar API become heavily used. Main thread, is the king, you end up « posting » a lot. Observable public final Observable<T> observeOn(Scheduler scheduler); public final Observable<T> subscribeOn(Scheduler scheduler); AndroidSchedulers public static Scheduler mainThread(); Threads One particularity of the Android system, is that many operations have to run in the Main (UI) thread. As RxJava was built for a multithreaded environments, it is easy to overcome this, using : • observeOn when you need the result to happen in a specific thread • subscribeOn when you need to processing to happen in a specific thread RxAndroid provides methods which will return a scheduler for the main thread (or for handler threads when needed).
  • 16. Memory leaks are bad. Calling UI outside the main thread is bad. Calling code when you Activity was destroyed is bad. public class MyActivity extends RxActivity { @Override public void onResume() { super.onResume(); myObservable .compose(bindToLifecycle()) .subscribe(); } } Lifecycle Using the Lifecycle components, you can extend Activity or AppCompatActivity, in order to be able to bind to a specific part of lifecycle. For example : resume / pause, create / destroy. Note that you will have to face weird casts on the compose depending on the data you observe.
  • 17. 3 Real Life Example ‘Cause it’s always better to use it for real… Let’s move on to a real world example, which will offer you a vision on how to use Rx and its extensions.
  • 18. Location, Location, Location… Let’s imagine you want to be able to listen to location changes from your application. Let’s say, your user can activate or reactive location, and change the rate at which location is updated. Let’s say you want your UI to be updated, and a database of the positions to be be populated. (which would be a very common case for a fitness app) If you were to make such a UI / app, which emitted data would you consider using ?
  • 19. GoogleApiClient : you will need it for using the FusedLocationApi LocationRequest : this guy tells the FusedLocationApi which kind of location will be helpful for you. Clicks : to the user’s command you will listen, young padawan. Players This game has 3 players : • You need to set up a GoogleApiClient, and get it "connected" only when you need to listen to locations. This class is giving you access to a set of APIs controlled by the Google Play Services. It needs to be initialized in a separate thread, let’s spare us some pain, and create an Observable. • You will then have a few parameters to give to the LocationServicesApi : these are LocationRequests. They will change as your user selects one of the options available, so we might have an observable for this too. • Your user will use a few buttons, which will be emitting events, we may need to convert. => Have a look a the code
  • 20. What Did We Learn ? Observables can be Hot or Cold, which roughly translates to active or passive. Operators will help you transform emitted values. Use Subscriptions it helps you avoiding mess. Observables can be emitted it may save you time and complexity. Android has its own extensions, use them! First, please do not take this example as the perfect source. It is merely an example, and I made some voluntarily specific uses of RX, so that you can see how many problems can be adressed. The first thing I’d like to underline is the fact that the Observables can be Hot or Cold. A Cold Observable is for example the Google Api Client one : it will only give a new GAC if you subscribe to it. A Hot Observable is for example the View Click one : clicks will happen, wether there is a subscriber or not. Subscriptions are the best tool when it comes to handling the lifecycle of your objects. Use them, you will avoid memory leaks, and other bugs. Emitted values can be transformed easily through black boxes se how I managed to get a Location Request from a ViewClickEvent. This transformed value is then emitted to the next item in the chain. Observables can be emitted : this is a tough one, but can be very helpful. For example, we get many LocationObservables, and use the switch operator to select the latest one. This helps wrapping up some APIs which are not letting you update their settings (or avoiding adding weird methods to do this). I have used some of the awesome Android extensions for RxJava : Listeners for the view, Lifecycle sanity, … USE THEM : you will save a lot of time, and a lot of boilerplate code.
  • 21. Clone https://github.com/saiimons/RxLocationTutorial I’ll let you guys checkout the code of this little demonstration
  • 22. Synthetic code Functional slices of code Android specifics Reusable components Replaceable blocks Advantages / Drawbacks Learning curve Readability Debugging Advantages : • If you like your code in synthetic, functional blocks, you will like Rx • It has libraries helping you integrating with Android : USE THEM • Your components can be reused / replaced : for testing or for evolutions of your app Drawbacks : • It can be painful to learn and discover all the Observable methods • A neophyte will find it hard to understand (though you should definitely write documentation) • Debugging can be a little bit tricky, because of some lengthy stack traces
  • 23. Observable<Question> questions = Observable.create(people); questions.subscribe( new Action1<Question>() { @Override public void call(Question question) { Simon.answer(question); } } ); Questions If you have any questions, now is the time !
  • 24. Thank You! Share if you liked this deck! @Saiimons