owned this note
owned this note
Published
Linked with GitHub
# RxAndroid and Retrofit
RxJava is a Java VM implementation of ReactiveX, which is a library for composing asynchronous and event-based programs by using observable sequences.
It extends the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) to support sequences of data and/or events and adds operators that allows these sequences to be composed together declaratively, while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures and non-blocking I/O.
## RxJava Basics
The two major components of reactive programming are `Observables` and `Observers`. `Observables` are producers, they emit item(s) that are consumed by `observers`. An observable may emit any number of items and then it terminates either by completing successfully or due to an error. `Observers` subscribe to an `Observable` which in turn, notifies subscribed Observers of an available item by calling a method on the observers. The Observer then reacts to whatever item or sequence of items the Observable emits. The Observable calls `Subscriber.onNext()` a number of times while emitting, followed by either `Subscriber.onComplete()` or `Suscriber.onError()`. Both `onComplete()` and `onError()` are called exactly once and at this point the Observable stops emitting. In summary, the `subscriber/observer` implements the these below methods to interact with an `Observable`:
* `onNext(data)`: Receives emitted data from the Observable
* `onError(Exception)`: Called when an error occurs. No further call is made at this point.
* `onCompleted`: Called when Observable is done emitting i.e when `onNext()` has been called for the last time.
To connect an `Observer` to an `Observable`, the `subscribe` method is used. What makes Observables very powerful are the operators that allows the sequences of items emitted, to be combined, transformed and manipulated before delivering to the Observer(s).
## Creating Observables
In `RxJava`, `Observables` can be created in a number of ways, few of which are show below:
1. **Observable.just():** convert an object or several objects into an Observable that emits that object or those objects.
```java
Observable.just("Hello RxAndroid");
//emits "Hello RxAndroid" to all subscribers
```
2. **Observable.from():** convert an Iterable, a Future, or an Array into an Observable.
```java
Observable.from(Arrays.asList(new String[]{"red","orange","yellow","green","blue"}))
//emits the string "red", "yellow", "green" and "blue", in that order.
```
3. **Observable.create():** creates an Observable from scratch by means of a function. We simply implement the `OnSubscribe` interface and tell the observable what it should do when subscriber(s) subscribe to it. A well-formed finite Observable must attempt to call either the observer’s `onCompleted` method exactly once or its `onError` method exactly once, and must not thereafter attempt to call any of the observer’s other methods.
```java
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(final Subscriber<? super Integer> subscriber){
for (int j = 0; j < 5; j++) {
subscriber.onNext(j);
}
subscriber.onCompleted();
}
});
//the observable starts to emits integers when an observer subscribes to it
```
For a complete list of the different ways of creating an `Observale`, check out this [link](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables).
## Subscribing an Observer to an Observable
`RxJava` provides the `subscribe` funcion which is used to subscribe an `observer` to an `Observable`. Fisrt, we create an `Observer` by implemeting `onNext()`, `onCompleted()` and `onError()` from the Subscriber interface, then we tell the `Observer` on which thread we want to observe and subscribe. RxAndroid gives us Schedulers, through which we can specify the threads. For example:
```java
Observable.from(Arrays.asList(1,2,3,4,5))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread()))
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
//called on completion
}
@Override
public void onError(final Throwable e) {
//called when error occurs
}
@Override
public void onNext(final String s) {
Log.d("emit", s);
}
});
```
Here are the things to note from the code above
* `subscribeOn(Schedulers.newThread())`: This will make the `Observable` do its background work in a new thread
* `.observeOn(AndroidSchedulers.mainThread()))`: This makes the subscriber action to execute its result on Android's main UI thread. This is very important especially when change to a UI component needs to be made based on the resut.
* `.subscribe()`: Subscribes an `Observer` to the `Observable`. The `Observers` `onNext` method is called on each emitted item, followed by either `onCompletion` if it runs successfully or `onError` if an error occurs.
## RxAndroid
[RxAndroid](https://github.com/ReactiveX/RxAndroid) is an extension to [RxJava](https://github.com/ReactiveX/RxJava) built for Android. It contains Android-specific bindings for RxJava. It adds a number of classes to RxJava to assist in writing reactive components in Android applications.
* It provides a `Scheduler` that schedules an `Observable` on a given Android `Handler` thread, particularly the UI thread.
* It provides operators that makes it easier to deal with `Fragment` and `Activity` life-cycle callbacks.
* It provides reusable, selft contained, reactive components for common Android use cases and UI concerns such as Button clicks etc.
#### Observing response of Async calls
On Android, asynchronous tasks are dealt with by observing their result on the main UI thread. This is typically done using an `AsyncTask` on vanilla Android. With RxJava, an `Observable` can be declared to be observed on the main thread using the `observeOn` operator. For example:
```java
public class DemoFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Observable.from(Arrays.asList(new String[]{"blue", "red", "yellow", "orange"}))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(/* add observer */)
}
}
```
The example above is a specialization of a more general concept which is binding communication to an Android message loop by using the `Handler` class. An `Observable` can be observed on an arbitrary thread and to do this, you create a `Handler` bound to that thread and use the `AndroidSchedulers.handlerThread` scheduler.
```java
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(); //bound to this thread
Observable.from("one, "two", "three", "four")
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.handlerThread(handler))
.subscribe(/* add observer */)
}
}, "custom-thread").start();
```
The Observable executes on a new thead and emits results `onNext` on the `custom-thread`. Alternatively, we could have used `observeOn(Schedulers.currentThread())` to observe on the current thread.
#### Activity and Fragment Life-cycle
One of the problems we face with handling background operations with `AsyncTask` is how to handle responses when our `Activity` or `Fragment` is no longer in the foreground, or the user rotates the device. If it is just a fire and forget call, then there is no problem, but when the result of the task is used to update the UI, we either get a `NullPointerException` while trying to access a UI component that no longer exists or we leak memory. RxAndroid provides an elegant way of dealing with this problem by using `Subscriptions` and a number of `Observable operators`. When an `Observer` subscribes to an `Observable`, a `Subscription` is returned and this can be used to unsuscribe from the `Activity` or `Fragment` in the `onDestroy` life-cycle callback method. For example,
```java
//subscription object
private Subscription subscription;
protected void onCreate(Bundle savedInstanceState) {
this.subscription = observable.subscribe(this);
}
....
protected void onDestroy() {
this.subscription.unsuscribe(); //unscubscribe
super.onDestroy();
}
```
This ensures that all references to the `Observer` will be released as soon as possible, and no more notifications will arrive at the `Observer` through `onNext`.
If an `Activity` is destroyed due to a change in configuration such as change in screen orientation, the `Observable` will fire again in `onCreate` and this will result in duplication of work because the same API call will be made again. All progress made initially will be lost. To solve this problem, `RxJava` provides the `cache()` or `replay()` Observable operators. In particular, `cache()` (or `replay()`) will continue the underlying request (even if you unsubscribe). Also, items emitted by the `Observable` during the span when it was detached from the `Activity` will be "played back", and any further notifications from the `Observable` will be delievered as usual.
While `cache()` auto-connects and replays all emmitted items from the `Observable`, `replay()` can have more parameterization and can do bounded time/size replays, by allowing setting of a maximum buffer size. Also, because `replay()` returns a [connectable Observable](http://reactivex.io/documentation/operators/replay.html), `connect` operator must be explicitly called on the observable in order to observe its emissions.
It is also very import to ensure that the `Observable` does not get destroyed in the `Activity` lifecycle. The `Observable` must be stored somewhere outside the lifecycle (a retained fragment, a singleton etc).
```java
Observable<String> observable = service.getInfo().cache();
Subscription subscription = observable.subscribe(string -> handleResponse(string));
//... when the activity is being recreated
subscription.unsubscribe();
//... once the Activity has been recreated
observable.subscribe(string -> handleResponse(string));
```
It is worthy to note that same Cached `observable` is used to re-subscribe after the `Activity` was re-created.
`CompositeSubscription` can be used to hold multiple subscriptions to `Observables`, and unsubscribe all at once when the `unsubscribe` method is called, mostly when the `Activity` is being destroyed. Once `unsubscribe()`has been called on a `CompositeSubscription`, any `Subscriptions` added to the `CompositeSubscription` from that point on will also be unsubscribed.
## RxBinding
RxBinding is a set of libraries that allow you to react to user interface events via the RxJava Paradigm. For example, we normally react to a click event on Android like this:
```java
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//handle on click here
}
});
```
Using `RxBinding`, same can be accomplished with `RxJava` subscription:
```java
Button button = (Button)findViewById(R.id.button);
Subscription buttonSub = RxView.clicks(button).subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
//handle on click here
}
});
// make sure to unsubscribe the subscription.
```
Another example handling text change on an EditText. Vanila android:
``` java
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// do some work with new text
}
@Override
public void afterTextChanged(Editable s) {
}
});
```
Same thing written with RxBinding support:
```java
EditText editText = (EditText)findViewById(R.id.editText);
Subscription editTextSub = RxTextView.textChanges(editText).subscribe(new Action1<String>() {
@Override
public void call(String value) {
// do some work with new text
}
});
// make sure to unsubscribe the subscription.
```
#### Benefits of RxBindings
`RxBindings` help to bridge non-reactive android APIs in an rx-friendly way. Anywhere you might have had callback or listener hell, you can instead replace them with `RxBinding` calls and maintain a consistent reactive architecture. It provides a more efficient way of mapping listeners to observables.
With RxBindings, you can easily compose multiple operations on a view using `observable operators`, in a case where you need to perform multiple actions in response to a view interaction.
For example, if you have a `SearchView`, and your app should make an api call to fetch results related to the search term, if the term is at least three characters long, and there has been at least a 100 milliseconds delay since the user last modifed the seacrh term in the view. To achieve this using standard Android code, you'll need to use a combination of both `listeners`, `Handlers` and `AsycTask`. With `RxBinding`, you can easily use the reactive architecture and operators to achieve this in a cleaner, less verbose and more understandable way:
```java
RxTextView.textChanges(searchTextView)
.filter(new Func1<String, Boolean> (){
@Override
public Boolean call(String s) {
return s.length() > 2;
}
})
.debounce(100, TimeUnit.MILLISECONDS)
.flatMap(new Func1<String, Observable<List<Result>>>() {
makeApiCall(s);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(/* attach observer */);
```
With Lambda expressions, the code above can be made shorter and cleaner.
To use RxBinding in your project, for basic support of `platform classes`, add the following line to your module level `build.gradle` file:
```groovy
compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
```
for 'support-v4' library bindings:
```groovy
compile 'com.jakewharton.rxbinding:rxbinding-support-v4:0.4.0'
```
for 'appcompat-v7' library bindings:
```groovy
compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.4.0'
```
Check out this [link](https://github.com/JakeWharton/RxBinding) to learn more about `RxBinding`.
## Using Java 8 Lambda Expressions
Lambda expressions make working with RxJava clean and very convinient. It helps to eliminate boiler plate code that makes the syntax verbose and less clear. For example, take a look at the code below for creating an Observable and subscribing an Observer to it. First without lambdas and secondly with lambdas.
**creating and subscribing to an observable without lambdas**
```java
Observable.just("Hello RxAndroid")
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d("Emitted", s);
}
});
```
**same code above with Lambda Expression**
```java
Observable.just("Hello RxAndroid")
.subscribe(s -> Log.d("Emitted", s));
```
#### Setting up Lambda Expressions in your Android code
To use java 8 Lambda expressions in your android code, you can either use the `Gradle Rerolambda` plugin developed by Evan Tatarka or use the new [Android Jack toolchain](https://source.android.com/source/jack.html).
**To use Retrolambda**
* Open the root `build.gradle` file and add the following dependency:
```groovy
classpath 'me.tatarka:gradle-retrolambda:3.2.5'
```
The complete `build.gradle` file should look like this:
```groovy
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-beta5'
classpath 'me.tatarka:gradle-retrolambda:3.2.5'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
```
* Modify the app module `build.gradle` file to apply the **me.tatarka.retrolambda** plugin:
``` groovy
apply plugin: 'me.tatarka.retrolambda'
```
* Add a new `compileOptions` block, then `sourceCompatibility` and `targetCompatibility` Java version should be set as 1.8
```groovy
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
```
* Set Java 8 JDK path in `retrolambda` block:
```groovy
retrolambda {
jdk '/path/to/java-8/jdk'
}
```
**Complete** `build.gradle` file:
```groovy
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.android.sample.rxandroidandretrofit"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
retrolambda {
jdk '/usr/lib/jvm/java-8-openjdk-amd64'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
}
```
Sync your project and you should be ready to use lambda expressions in your project.
One important disadvantage of using `Retrolambda` as pointed out by Jake Wharton is that, the code in your IDE won't match the code running on the device because `Retrolambda` rewrites the byte code to back-port lambda functionality.
Known issues with using retrolambda plugin can be found [here](https://github.com/evant/gradle-retrolambda).
**Using the new Android Jack toolchain**
Android provided a way to use some Java 8 language features including `lambda expressions` in your Android project by enabling the **Jack toolchain**. To do this, edit your module level `build.gradle` file as follows:
```groovy
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
```
Sync your gradle file, if you encounter any build error, you may need to download the latest `Android SDK Build-tools` from the `SDK Manager`.
**Known issues with using the Jack toolchain**
Android studio instant run does not currenty work with Jack and will be disabled while using the new toolchain. Because Jack does not generate intermediate class files when compiling an app, tools that depend on these files for example, Lint detectors, do not currently work with Jack. Also tools like `android-apt` which is required for using `Dagger 2` in your Android project does not currently work with Jack.
## Retrofit
Retrofit is a popular REST client for Android. It makes it easy to interact with an HTTP API by turning it into a Java interface. Retrofit has a built in support for RxJava because `Observables` can be returned directly from method calls. To use Retrofit and return `Observables`, we do the following:
* Add `Retrofit` dependencies to our `build.gradle` file
* Create a Model(POJO) for the expected response from our API call.
* Create an interface for the API calls.
* Create the `Retrofit` instance.
* Make the API call
To demonstrate this, I will be writing a sample code that queries the Github API with `Retrofit` and returns an `Observable`.
#### Step 1: Add gradle dependencies
For RxAndroid we add:
```groovy
//rx android
compile 'io.reactivex:rxandroid:1.2.0'
//rx java
compile 'io.reactivex:rxjava:1.1.5'
```
Retrofit dependencies:
```groovy
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.0.2'
//retrofit gson converter
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
//retrofit adapter
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
```
In other to return an `Observable` from our `Retrofit` calls, we need to use a different call adapter called `RxJavaCallAdapter`. This was why we needed to add this line `compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'` to our `build.gradle` file.
#### Step 2: Create a Model for the API response
The API url we want to call is this:
`https://api.github.com/users/mayojava` and the response from the call looks like this:
```javascript=
{
"login": "mayojava",
"id": 3038239,
"avatar_url": "https://avatars.githubusercontent.com/u/3038239?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/mayojava",
"html_url": "https://github.com/mayojava",
"followers_url": "https://api.github.com/users/mayojava/followers",
"following_url": "https://api.github.com/users/mayojava/following{/other_user}",
"gists_url": "https://api.github.com/users/mayojava/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mayojava/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mayojava/subscriptions",
"organizations_url": "https://api.github.com/users/mayojava/orgs",
"repos_url": "https://api.github.com/users/mayojava/repos",
"events_url": "https://api.github.com/users/mayojava/events{/privacy}",
"received_events_url": "https://api.github.com/users/mayojava/received_events",
"type": "User",
"site_admin": false,
"name": "Adegeye Mayowa",
"company": "Konga Online Shopping Limited",
"blog": null,
"location": "Nigeria",
"email": "mayox4ever2006@gmail.com",
"hireable": null,
"bio": null,
"public_repos": 25,
"public_gists": 0,
"followers": 6,
"following": 5,
"created_at": "2012-12-14T00:29:45Z",
"updated_at": "2016-02-27T05:10:48Z"
}
```
To make creating a Java Model from a JSON response easier, `jsonschema2pojo` provides a service that does that quite easily. Head over this [website](http://www.jsonschema2pojo.org/) and paste the JSON. Select `JSON` as the source style and `GSON` as the annotation style. You can click on the preview button to view the created model, or just click on the zip button to download the created model(s).
![](https://i.imgur.com/7I13HnK.png)
Copy the downloaded java file(s) into any convinient folder in your project.
#### Step 3: Create an interface for the API calls
We are going to be making just once call, `getUser`, so our interface will have a single method.
```java
GithubService.java
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
public interface GithubService {
@GET("users/{user}")
Observable<Model> getUser(@Path("user") String githubUsername);
}
```
Each endpoint in the interface must specify an annotation of the HTTP method `(GET, POST, PUT etc)` for that call. The method parameters can also have special annotations like `(@Query, @Path, @Body etc.)`
`@Query`: Specifies the query key name with the value of the annotated parameter
`@Path`: Subsities for varibale in the API endpoint URL. In the example above, the method parameter `githubUsername` will replace `{user}` in the API URL.
`@Body`: Payload for a POST call
#### Step 4: Create Retrofit instance
To create the Retrofit instance, we use the `Retrofit builder`, specifying the github api url `https://api.github.com` as the base url,`Gson` as the converter library and `RxJavaCallAdapterFactory` as the call adapter.
```java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
```
The purpose of the call adapter factory, is to mae Retrofit return `Observables` from the method calls.
#### Step 5: Make API call with Retrofit
To make API calls with the retrofit instance, we create an instance of the interface using the retrofit object we created in the previous step, and then invoke methods in this instance.
```java
GithubService service = retrofit.create(GithubService.class);
service.getUser("mayojava")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(model -> {
Toast.makeText(getBaseContext(), model.getEmail(), Toast.LENGTH_SHORT).show();
});
```
The API call runs on a new thread created by the `Schedulers.newThread()` function and the response is received on the main UI thread.
The complete code can be found in this [github repo](https://github.com/mayojava/RxAndroidAndRetrofit).
## References
[https://github.com/ReactiveX/RxJava/wiki/The-RxJava-Android-Module](https://github.com/ReactiveX/RxJava/wiki/The-RxJava-Android-Module)
[http://reactivex.io/intro.html](http://reactivex.io/intro.html)
[https://github.com/JakeWharton/RxBinding](https://github.com/JakeWharton/RxBinding)
[https://realm.io/news/donn-felker-reactive-android-ui-programming-with-rxbinding/](https://realm.io/news/donn-felker-reactive-android-ui-programming-with-rxbinding/)
[http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/](http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/)