Why is RxJava often used with Retrofit?

谁说我不能喝 提交于 2021-02-17 08:36:50

问题


What is the benefit of using Retrofit in combination with Rxjava?


回答1:


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.




回答2:


To understand those advantages, you must first understand how beneficial it is for your codebase to adopt Reactive Extensions.

  • Composability and transformation

    • Streams offer very composable interface. It allows you to perform transforming ( on the structure and time of the event ) operations and basically interact ( such as making dependencies or leveraging result/error from another stream ) between various streams seamlessly. Although you can do this with callbacks, if you try to implement a more complicated use-case, which can be even as simple as 3 requests, the code will lose its readability very quickly. On the other hand, Rx lets you implement very complex scenarios and still look smooth.
  • Threading and asynchronous operations

    • Rx gives you a very granular control over which threads will be used to perform work in various points within a stream. To point the contrast here already, basic call approach used in Retrofit is only scheduling work on its worker threads and forwarding the result back into the calling thread. When declared as a stream, retrofit doesn't handle threading and leaves it to you only which gives you the control.
  • Rx libraries

    • As you might have seen already, there are countless libraries out there that leverage the Reactive extensions and implement various functionality as a stream. You can easily take advantage of them when working with your requests

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.



来源:https://stackoverflow.com/questions/42218189/why-is-rxjava-often-used-with-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!