Retrofit & RxJava multiple requests complete

后端 未结 4 2263
盖世英雄少女心
盖世英雄少女心 2021-02-14 10:25

I need to do:

  1. Request 2 lists of news from different websites
  2. Combine results from requests
  3. Sort items by date
  4. Get 10 newest news
  5. <
4条回答
  •  不知归路
    2021-02-14 10:55

    You can use zip operator to call 2 requests async and save or process their data on response.

    For example.

    Below are two Observable

    Observable responseOneObservable = getRetrofitClient().getDataOne()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());
    
    Observable responseTwoObservable = getRetrofitClient().getDataTwo()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());
    

    Using zip operator on above two Observable as below.

    Observable> testDataObservable = Observable.zip(responseOneObservable, responseTwoObservable, new Func2>() {
                @Override
                    public ArrayList call(ResponseOne responseOne, ResponseTwo responseTwo) {
                      ArrayList testDataList = new ArrayList();
                          // process data from response responseOne & responseTwo
                      return testDataList;
                } 
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber>() {
    
            @Override
            public void onNext(ArrayList testDataList) {
    
            }
    
            @Override
            public void onCompleted() {
                Log.d(TAG, "onCompleted" ); 
                // you can show alert here or do something when completed 
            }
    
            @Override
            public void onError(Throwable t) {
                Log.d(TAG, "onError Throwable: " + t.toString() );
            }
        });
    

提交回复
热议问题