簡體   English   中英

使用rxJava2在hashmap上合並了多個Retrofit2請求

[英]Multiple retrofit2 requests merged on hashmap with rxJava2

我有一個對象列表: ArrayList<T> arrayList; 在列表的每個對象上都有一個ID: T.getId() ,我需要它才能發出請求。 作為響應,將提取另一個對象列表: ArrayList<E> anotherList

我想基於id: T.getId()和每個響應進行多次調用,我想將該對象: T與響應:哈希ArrayList<E> anotherList上的ArrayList<E> anotherListHashmap<T, ArrayList<E> anotherList>並在所有請求完成后返回該值。 有沒有辦法可以使用rxJava實現此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()) T ,在Hashmap<T, ArrayList<E> anotherList>上響應ArrayList<E> anotherList 所有請求完成后,返回包含這些對的最終hashmap

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

我有辦法實現這一目標嗎?

我認為您可以創建一個字段: 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它的使用,以獲得每個項目arrayListflatMap允許您使用的每個項目創建一個相關的可觀察到的,你需要的。

然后使用DisposableObserver在onNext回調上獲得中間完成的HashMap<Integer,ArrayList<E>> ,在onCompleted回調上獲得完全完成的HashMap

希望這可以幫助。

對不起我的英語不好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM