#2 ~ Getting Started with RxJava in Android

Image 1. Getting Started with RxJava

In previous article i wrote about intro with RxJava. In this article i want to dig deeper how to integrated our Android Application with RxJava and combine it with Retrofit.

Before, go more further i expect you have knowledge about Retrofit, if not just googling it.


As usual, like other depedencies. first we should add RxJava and RxAndroid in Gradle, which will looks like this.

compile 'com.squareup.okio:okio:1.6.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.4.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.6'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'

Second. Add RxJavaCallAdapterFactory in you retrofit helper, which will looks like this.

private Retrofit buildRetrofit() {
return new Retrofit.Builder()
.baseUrl(ApiConstant.BASE_URL)
.client(buildHttpClient())
.addConverterFactory(GsonConverterFactory.create(buildGson()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}

Third, in you service interface, use like this.

@GET("FooUrl1")
Observable<Bar1> getBar1(
@Query("count") int count,
@Query("page") int page
);

Four, in you Interactor which i use MVP Design Pattern (we will talk this in later article). use like this.

public Observable<Bar1> getBar1() {
return service.getBar1(4, 1)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
getBar1().subscribe(new SimpleObserver<Bar1>() {
@Override
public void onCompleted() {
super.onCompleted();
setRefreshing(false);
}

@Override
public void onNext(Bar1 response) {
super.onNext(response);
setRefreshing(false);

clearAdapter();
bindUI(response);
}

@Override
public void onError(Throwable e) {
super.onError(e);
setRefreshing(false);

DialogFactory.toast(mContext, "Info", e.getMessage());
}

@Override
public String getTag() {
return TAG;
}
});

The SimpleObserver is my custom class which extend from Observer<T>.

Hope you enjoy with this article. for further info, just comment or email me at gumay[dot]raditya[at]gmail[dot]com.

@r_adiit | Github | Linkedin