2017-02-23 70 views
0

我有一個對象列表:ArrayList<T> arrayList;,並且在列表的每個對象上都有一個Id:T.getId()我需要提出請求。作爲響應對象的另一個列表是牽強:ArrayList<E> anotherList使用rxJava2在hashmap上合併多個retrofit2請求

我想根據id進行多次電話:T.getId()和每一個迴應,我想合併一個對象:在一個HashMap ArrayList<E> anotherListT與響應Hashmap<T, ArrayList<E> anotherList>和在所有請求完成後返回值。有沒有一種方法,我可以做到這一點使用rxJava

//For every `T.getId()`, fetch `ArrayList<E> anotherList` 
for(int i=0; i<arrayList.size(); i++){ 
    T object = arrayList.get(i); 
    fetchData(T.getId()); 
} 

onNext()合併(hashmap.put())THashmap<T, ArrayList<E> anotherList>響應ArrayList<E> anotherList。畢竟請求返回完最後hashmap包含那些對:

retrofit.fetchData(T.getId()) 
     .subscribeOn(Schedulers.io()) 
     .observeOn(AndroidSchedulers.mainThread()) 
     .flatMap(...) 
     .merge(...) 
     .subscribeWith(...) 

有沒有一種方法,我可以做到這一點?

回答

0

我想你可以創建一個領域: private HashMap<Integer,ArrayList<E>> mHashMap;

一旦這個領域進行實例化,你可以嘗試:

Observable.just(arrayList) 
       .flatMapIterable(new Function<ArrayList<T>, Iterable<? extends T>>() { 
        @Override 
        public Iterable<? extends T> apply(ArrayList<T> ts) throws Exception { 
         return ts; 
        } 
       }).flatMap(new Function<T, ObservableSource<Hashmap<T,ArrayList<E>>>>() { 
        @Override 
        public ObservableSource<Hashmap<T,ArrayList<E>>> apply(T t) throws Exception { 
         return Observable.fromCallable(new Callable<Hashmap<T,ArrayList<E>>>() { 
          @Override 
          public Hashmap<T,ArrayList<E>> call() throws Exception { 
           mHashMap.put(t, fetchData(t.getId())); 
           return mHashMap; 
          } 
         }); 
        } 
       }); 

flatMapIterable它的使用得到了arrayList的每個項目,flatMap允許您使用每個項目來創建您需要的相關可觀察項。

然後用DisposableObserver就要上onNext回調中間完成HashMap<Integer,ArrayList<E>>並在onCompleted回調全面完成HashMap

希望這有助於。

對不起,我的英語。

相關問題