首页 > 解决方案 > Chain Single independent requests with RxJava

问题描述

I have a method to add an item to my account:

 fun addItem(@Body addExperience: AddItem): Single<Item>

at some point the user can select multiple items and then add them all in bulk to his account. I want to chain these independent calls with RxJava2 (possibly in parallel) and then use the result of each to increment a progress bar.

Problem is --- i have no idea how to do it! Would this possibly be a Flowable? how can I generate this flowable from the multiple singles?

标签: androidretrofit2rx-java2

解决方案


我建议使用Flowable.fromIterable()flatMapSingle()每个请求。您可以通知用户有关进度,因为在每个请求之后都会调用subscribeonNext。

List<Single<Integer>> list = new ArrayList<>();
list.add(Single.just(1));
list.add(Single.just(2));
list.add(Single.just(3));
list.add(Single.just(4));

Flowable.fromIterable(list)
        .flatMapSingle(singleRetrofitRequest -> singleRetrofitRequest, false, 2)
        .subscribe(item -> System.out.println(item));

如您所见,我添加了额外的参数来flatMapSingle()表示可能的并行请求数。


推荐阅读