使用RxJava + Retrofit 2的正确方法 [英] Right way of using RxJava + Retrofit 2

查看:814
本文介绍了使用RxJava + Retrofit 2的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JSON:

{  
"success":true,
"data":[  
   {  
      "id":"29",
     "name":"\u0420\u0435\u0441\u0442\u043e\u0440\u0430\u0446\u0456\u044f \u0411\u0430\u0447\u0435\u0432\u0441\u044c\u043a\u0438\u0445 \/ Baczewski Restaurant",
     "street":"\u0432\u0443\u043b.    \u0428\u0435\u0432\u0441\u044c\u043a\u0430, 8",
     "latitude":"49.842292845502",
     "longitude":"24.029848249565",
     "image":"https:\/\/i.onthe.io\/j9aocq72r2lfsmoh9.r500x500.01ff9fff.jpg"
     },
     ...
    ]
    }

根据它必须以架构将Classes(pojo)创建到pojo.第一个提供了从data数组->

According to it have to Classes (pojo) created with schema to pojo. First one provides method to get data from data array - >

public List<Datum> getData() {
    return data;
}

第二个是此数据的model.

仅使用改造2.0时,我会执行call,解析data数组中的每个object,并将其添加到RecyclerView.Adapter

While using only retrofit 2.0 I perform a call, parse each object from the data array and add it to RecyclerView.Adapter

Call<PlaceList> call = service.list(1, offset, 10);
call.enqueue(new Callback<PlaceList>() {
        @Override
        public void onResponse(Call<PlaceList> call, Response<PlaceList> response) {
            final int size = response.body().getData().size();
            for (int i = 0; i < size; i++) {
                places.add(response.body().getData().get(i));
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (offset == 0)
                        //   adapter.notifyItemRangeInserted(0, foodDataList.size());
                        placeRecyclerAdapter.notifyDataSetChanged();
                    else
                        placeRecyclerAdapter.notifyItemRangeChanged(places.size() - size, places.size());
                }
            });

        }

        @Override
        public void onFailure(Call<PlaceList> call, Throwable t) {

        }
    });  
    _______________

    public interface Places {
@GET("places.getPlaces")
Call<PlaceList> list(
        @Query("type") int type,
        @Query("offset") int offset,
        @Query("limit") int limit);
       }

所以这对我来说是一种通常的方式.现在,我想使用RxJava做同样的事情.

So this a usual way for me. Now I want to do the same using RxJava.

这是我的interface:

public interface Places {
@GET("places.getPlaces")
Observable<PlaceList> list(@Query("type") int type,
                             @Query("offset") int offset,
                             @Query("limit") int limit);
}

这就是我执行call的方式:

  Observable<PlaceList> call = service.list(1, offset, 10);
    subscription = call.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<PlaceList>() {
                @Override
                public void onCompleted() {
                    System.out.println("onComplete");
                }

                @Override
                public void onError(Throwable e) {
                    System.out.println("onError");
                    e.printStackTrace();
                }

                @Override
                public void onNext(PlaceList data) {
                    placeRecyclerAdapter.addData(data.getData());
                }
            });

是的,它也可以使用,但这是使用Rx的正确方法吗?我试图比较分析所需的时间,但没有发现任何显着差异. 在阅读了几篇文章之后,我才刚刚开始学习RxJava.那么感受RxJava力量的正确方法是什么?

Yeah, it's also works, but was it a right way of using Rx? I tried to compare time needed for parsing, but didn't see any notable difference. I'm just on my first day of studying RxJava, after reading few articles. So what is the right way to feel the power of RxJava?

推荐答案

您正确使用它,RxJava具有强大的功能,可以利用它来提高性能.

You are using it correctly, RxJava has very much power which you can leverage in order to improve Performance.

在哪里使用? 1.关于用户事件,例如按钮单击,按键事件 2.响应延迟绑定的IO.磁盘/网络读/写 3.硬件/传感器触发的事件

Where to use? 1. On user events, like Button click, Key events 2. Respond to latency bound IO. Disk/network read/write 3. Events triggered by Hardware/sensors

不应从Observable create手动启动Thread.

Should not start Thread manually from Observable create.

使用RxJava改造网络通话: 使用单个:,因为我们的API不会分多次或多次提供数据.相反,它将在一次调用中发出所有内容. 因此,在出现Observable的情况下,onNext()一旦发生,onCompleted()就会随之而来. 因此,最好使用Single进行API调用.

Retrofit Network call with RxJava: Use Single : As our API will not give data in a pieces or multiple times. Instead it will emit everything in just one call. So, in case of Observable onCompleted() will follow as soon as onNext() happens. So, it would be better to use Single for API calling.

使用Completable:每当我们仅需要通过API将数据更新到Server时,我们就不会理会结果如何.我们只是说服务成功与否.在这种情况下,我们不希望发出任何东西.因此,在这种情况下,建议使用Completable.

Use Completable : Whenever we need to just update data to Server through API, and We do not bother about what should be the result. We just meant if service is successful or not. In this cases we are not expecting to emit anything. So use of Completable is encouraged in the cases.

对于进度视图隐藏/显示: 将这两个事件与doOnSubscribe()和doFinally()绑定. 这是两个运算符,因此我们可以在逻辑上将它们与RxCall绑定.

For progress view hide/show: Bind this two events with doOnSubscribe() and doFinally(). This are two operators, so we can logically bind them with RxCall.

RxJava错误处理:

onErrorResumeNext()— 指示Observable在遇到错误时发出一系列项目(这是另一个Observable)

onErrorResumeNext( ) — instructs an Observable to emit a sequence of items (which is another observable)if it encounters an error

onErrorReturn()— 指示Observable在遇到错误时发出特定项

onErrorReturn( ) — instructs an Observable to emit a particular item when it encounters an error

onExceptionResumeNext()— 指示Observable在遇到异常(但不是其他各种throwable)后继续发射项目

onExceptionResumeNext( ) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)

retry()— -如果源Observable发出错误,请重新订阅该消息,以希望它可以完成而不会出错. 在这里,我们还可以传递有关应重试多少次的论点. 喜欢.重试(4).它将重试四次,此后如果再次发生错误,则会引发错误.

retry( ) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error. Here we can also pass argument for How many times retry should happen. Like. retry(4). It will retry four times and after that if again error occures then will throw an error.

retryWhen()— -如果源Observable发出错误,则将该错误传递给另一个Observable,以确定是否重新订阅源

retryWhen( ) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source

用于视图绑定的RxAndroid:

认为反应活跃: 我们可以将RxJava用于所有视图事件,包括单击事件,滚动事件,拖动事件. 简而言之,我们可以将所有侦听器替换为RxJava observable.

Think Reactive: We can use RxJava for all view events including click event, scroll event, drag event. In short, we can replace every Listeners with RxJava observables.

可在查看级别使用的库: RxBinding,RxSupport-v4,RxAppCompat-v7,RxRecyclerView,RxDesign,RxLeanBack.

Available Libraries to use at View level: RxBinding, RxSupport-v4, RxAppCompat-v7, RxRecyclerView, RxDesign, RxLeanBack.

具有MVP的RxBinding: 我们将从View返回Observable. 此可观察对象将获取到Presenter并在Presenter上进行订阅.

RxBinding with MVP: We will return Observable from View. This observable will fetch to Presenter and will do Subscription at Presenter.

RxAdapter :我们可以将其用于Adapter中的数据更改事件.通常可用于Android Listview. RxRecyclerView:对于recyclerview适配器数据更改事件,我们可以使用它.

RxAdapter: we can use this for data change event in Adapter. Typically available for Android Listview. RxRecyclerView: For recyclerview adapter data change events we can use this.

这篇关于使用RxJava + Retrofit 2的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆