简体   繁体   中英

Multiple retrofit2 requests merged on hashmap with rxJava2

I have a list of objects: ArrayList<T> arrayList; and on every object of the list there is an Id: T.getId() whom I need for making a request. As a response another list of objects is fetched: ArrayList<E> anotherList

I want to make multiple calls based on the id: T.getId() and on every response I want to merge that Object: T with the response: ArrayList<E> anotherList on a hashmap: Hashmap<T, ArrayList<E> anotherList> and return the value after all requests has been finished. Is there a way i can achieve this using 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());
}

on every onNext() merge(hashmap.put()) T with response ArrayList<E> anotherList on Hashmap<T, ArrayList<E> anotherList> . After all requests finished return final hashmap containing those pairs:

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

Is there a way i can achieve this ?

I think you can create a field : private HashMap<Integer,ArrayList<E>> mHashMap;

Once this field was instanciate , you can try :

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 it's use to get each item of the arrayList and flatMap allows you to use each item to create a associated observable of that you need.

Then use a DisposableObserver to get on the onNext callback the intermediate completed HashMap<Integer,ArrayList<E>> and on the onCompleted callback the fully completed HashMap

Hope this helps.

Sorry for my english.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM