【问题标题】:Repeat request by Retrofit and RxRetrofit 和 Rx 的重复请求
【发布时间】:2016-05-14 01:06:41
【问题描述】:

我有按页面返回数据的 API,如下所示:

{
   "count": 100,
   "offset": 0,
   "limit": 25,
   "result": [{}, {}, {}...]
}

我需要获取所有页面 - 所有数据(以不同的“偏移量”执行查询:)。

      Observable<MyResponse> call = RetrofitProvider.get().create(MyApi.class).getData(0, 25); // limit and offset
    call.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.newThread())
            .doOnNext(<saving data>)
            .subscribe(result -> {                   
            }, error -> {             
            });

我正在尝试使用 RxAndroid 和 Retrofit。最好的方法是什么?

【问题讨论】:

    标签: android rx-java rx-android


    【解决方案1】:

    您可以使用发布主题作为源 observable,然后不断为下一个范围动态添加新请求。

    private Observable<ApiResponse> getData(int start, int end) {
        // Get your API response value
        return RetrofitProvider.get().create(MyApi.class).getData(0, 25);
    }
    
    public Observable<ApiResponse> getAllData() {
        final PublishSubject<ApiResponse> subject = PublishSubject.create();
        return subject.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                getData(0, SECTION_SIZE).subscribe(subject);
            }
        }).doOnNext(new Action1<ApiResponse>() {
            @Override
            public void call(ApiResponse apiResponse) {
                if (apiResponse.isFinalResultSet()) {
                    subject.onCompleted();
                } else {
                    int nextStartValue = apiResponse.getFinalValue() + 1;
                    getData(nextStartValue, nextStartValue + SECTION_SIZE).subscribe(subject);
                }
            }
        });
    }
    

    【讨论】:

    • 在 subject.onCompleted(); subscribe 方法从未被调用
    • 是的,很好,在 onComplete 之后,流将自动取消订阅。这可以通过仅传递 getData 观察者的 onNext 和 onError 调用(而不是订阅)来避免。
    【解决方案2】:

    如果你知道计数是多少,你可以做类似的事情

    Observable<MyResponse> call = Observable.empty();
    for (int i=0 ; i<count ; i+=25) { 
        call.concatWith(RetrofitProvider.get().create(MyApi.class).getData(i, i+25));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2017-07-19
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2015-12-11
      相关资源
      最近更新 更多