Why is RxJava often used with Retrofit?

Question

Retrofit Already in run on background thread. Then why need another background task RxJava?

I think most importanly, avoid nested callbacks(callback hell).

e.g) Callback hell (Retrofit)

public interface MyService
{
    @GET("users")
    Call<List<UserModel>> getUser();

    @GET("userinfo")
    Call<UserInfoModel> getUserInfoById(@Query("id") Integer id);
}

service.getUser().enqueue(new Callback<UserModel>() {

    @Override
    public void onResponse(Call<UserModel> call, Response<UserModel> response) {
        //process UserModel

        UserModel data = response.body();

        //if you want user infomation from server
        service.getUserInfo(data.getId()).enqueue(new Callback<UserInfoModel>(){
            //... is callback hell!!
        });

    }
    @Override
    public void onFailure(Call<UserModel> call, Throwable t) {
       //error handling
    }
});

e.g) Avoid Callback hell(Retrofit + RxJava)

public interface MyService
{
    @GET("users")
    Observable<List<UserModel>> getUser();

    @GET("userinfo")
    Observable<UserInfoModel> getUserInfoById(@Query("id") Integer id);
}

service.getUser()
    .flatMapIterable(list -> list)
    .flatMap(user -> service.getUserInfoById(user.getId()))
    .doOnNext(userinfo -> saveUserInfo(userinfo)).subscribe();

if you are using RxJava you can use Observable to avoid this situation.

Additional

The above code snippet is just an example.

In fact, RxJava contains much more observe pattern related features.

Additional – Benefit of Event-Driven Programming in Android (RxJava)

Most Android application are built with the based on user or data interaction. (e.g GUI updates when the interaction occurs). So we see these as a set of events and designing and building an application based on this is a very intuitive and appropriate for internal and external events.

Leave a Comment