【发布时间】:2019-06-20 21:01:25
【问题描述】:
在我的 android 应用程序中,我想使用改造和 rxjava 发出多个 http 请求来获取 json 数据。请求的数量取决于用户的偏好(1 到 40)。每个请求都是独立的并且返回相同的类型。所以,我尝试应用在这个问题 (How to make multiple request and wait until data is come from all the requests in retrofit 2.0 - android) 中推荐的方式,它使用 rx-java 的 zip 功能。但我找不到一种方法来获取和组合每个请求的结果。我在改造中用于单个请求的响应类型是Response<List<NewsItem>>,其中 NewsItem 是我的自定义对象。 (响应实际上是 json 数组,但在单个请求中改造会自动处理它并将其转换为我的自定义对象列表)到目前为止我尝试的内容如下:
我的 API 接口
public interface API {
String BASE_URL = "xxx/";
@GET("news/{source}")
Observable<List<NewsItem>> getNews(@Path("source") String source);
}
Viewmodel 类获取数据
public class NewsVM extends AndroidViewModel {
public NewsVM(Application application){
super(application);
}
private MutableLiveData<List<NewsItem>> newsLiveData;
public LiveData<List<NewsItem>> getNewsLiveData(ArrayList<String> mySourceList) {
newsLiveData = new MutableLiveData<>();
loadNews(mySourceList);
return newsLiveData;
}
private void loadNews(ArrayList<String> mySourceList) {
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
API api = retrofit.create(API.class);
//Gathering the requests into list of observables
List<Observable<?>> requests = new ArrayList<>();
for(String source: mySourceList){
requests.add(api.getNews(source));
}
// Zip all requests
Observable.zip(requests, new Function<Object[], List<NewsItem>>() {
@Override
public List<NewsItem> apply(Object[] objects) throws Exception {
// I am not sure about the parameters and return type in here, probably wrong
return new ArrayList<>();
}
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.subscribe(
new Consumer<List<NewsItem>>() {
@Override
public void accept(List<NewsItem> newsList) throws Exception {
Log.d("ONRESPONSE",newsList.toString());
newsLiveData.setValue(newsList);
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable e) throws Exception {
Log.d("ONFAILURE", e.getMessage());
}
}
).dispose();
}
}
它没有给出错误,但也没有给出响应,因为我无法处理响应。任何人都可以帮助我组合每个请求的结果吗?我搜索了所有问题,但找不到这样的示例。
【问题讨论】:
标签: android rx-java retrofit2 rx-java2