我正在学习RX Java,我希望将N个并行请求发送到Web API,并将合并后的结果合并到一个List中。我正在使用Retrofit和RXJava扩展来发送请求:
@GET("getForkliftDetail")
Observable<ForkliftDetail> getForkliftDetail(
@Query("lang") String language,
@Query("id") Integer forkliftId);
我发送请求的函数如下所示:
List<Observable<ForkliftDetail>> requests = new ArrayList<>();
for (Forklift item: forkliftParkList) {
requests.add(service.fetchForkliftDetails(locale, item.getId()));
}
Observable.zip(
requests,
new FuncN(){
public ForkliftDetail call(ForkliftDetail... args) {
Log.i("RX TEST", args.toString());
return new ForkliftDetail();
}})
// After all requests had been performed the next observer will receive the Object, returned from Function
.subscribe(
// Will be triggered if all requests will end successfully (4xx and 5xx also are successful requests too)
new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
//Do something on successful completion of all requests
}
},
// Will be triggered if any error during requests will happen
new Consumer<Throwable>() {
@Override
public void accept(Throwable e) throws Exception {
//Do something on error completion of requests
}
}
);
然而,我在这一点上陷入困境。 FuncN
错误说我需要实现call(Object...)
。我认为FuncN
方法是我可以将所有响应ForkliftDetail
对象添加到新列表并返回它的地方。请帮我理解这个。提前谢谢!
答案 0 :(得分:0)
试试这个:
List<Observable<ForkliftDetail>> requests = new ArrayList<>();
for (Forklift item: forkliftParkList) {
requests.add(service.fetchForkliftDetails(locale, item.getId()));
}
Observable.zip(
requests,
new Function<Object[], ForkliftDetail>() {
@Override
public ForkliftDetail apply(Object[] args) {
Log.i("RX TEST", Arrays.toString(args));
return new ForkliftDetail();
}
}
)
.subscribe(
new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable e) throws Exception {
}
}
);