为什么RxJava经常与Retrofit一起使用? [英] Why is RxJava often used with Retrofit?
问题描述
将Retrofit与Rxjava结合使用有什么好处?
What is the benefit of using Retrofit in combination with Rxjava?
推荐答案
问题
改造已在后台线程上运行.那为什么还需要另一个后台任务RxJava?
Retrofit Already in run on background thread. Then why need another background task RxJava?
我认为最重要的是,避免嵌套回调( callback hell
).
I think most importanly, avoid nested callbacks(callback hell
).
例如,回调地狱(改造)
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
}
});
例如,避免回调地狱(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();
如果您使用的是 RxJava
,则可以使用 Observable
来避免这种情况.
if you are using RxJava
you can use Observable
to avoid this situation.
其他
Additional
上面的代码段只是一个例子.
The above code snippet is just an example.
实际上, RxJava
包含更多与 observ pattern
相关的功能.
In fact, RxJava
contains much more observe pattern
related features.
附加功能-Android(RxJava)中的事件驱动编程的好处
Additional - Benefit of Event-Driven Programming in Android (RxJava)
大多数 Android应用程序
都是基于基于用户或数据的 interaction
构建的.(例如,发生交互时,GUI会更新).因此,我们将它们视为事件的集合
,并基于此设计和构建应用程序是非常直观的,并且适用于内部和外部事件.
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.
这篇关于为什么RxJava经常与Retrofit一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!