使用改造和RxJava(Android)组合来自多个API调用的数据

问题描述 投票:0回答:1

我想要做的是访问几个不同的URL数据,合并这些数据,然后在我的应用程序中使用它。我可以毫不费力地获取我需要的所有数据,但我无法弄清楚的是如何将数据组合到单个列表中并知道所有API调用何时完成(所有数据都在列表)。

这是我进行API调用的循环:

for(String diningCourt: diningCourts){
        menuApi.getMenu(diningCourt, date)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(responseData -> {

                     //I want to add responseData to a list with 
                     //the results from the rest of the calls 

                });
    }

收集数据的正确方法是什么?我已经尝试使用静态类变量来存储结果,但我最终只得到了来自其中一个API调用的数据。任何建议将不胜感激。

java android retrofit2 rx-java2
1个回答
1
投票

我们使用“combineLatest”参见http://reactivex.io/documentation/operators/combinelatest.html当这两个调用都完成时,这个操作符会执行两个调用并获得结果。

Observable.combineLatest(observable1, observable2, (result1, result2) -> { //use both results })
© www.soinside.com 2019 - 2024. All rights reserved.