What is the benefit of using Retrofit in combination with Rxjava?
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.
To understand those advantages, you must first understand how beneficial it is for your codebase to adopt Reactive Extensions.
Composability and transformation
Threading and asynchronous operations
Rx libraries
There are other advantages beside these, but you can tell that it is greatly beneficial to go reactive. Requests are very a good starting point to learn working with streams and gradually introduce more and more stream logic in your codebase.
It is not a substitution. RxJava and Retrofit are a perfect match, that's why there is native support for it in Retrofit in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With