需要执行api请求并下载作为响应返回的所有资产。 我有以下逻辑,但不确定完成此操作的正确方法是什么。
public Observable<Response> prepareSomething() {
return api.requestSomthing()
.observeOn(Schedulers.io())
.flatMap(response -> Observable.fromIterable(response.getAssetsList()))
.map(asset -> downloadAsset(asset, response.getSomeValue/*how?*/))
.someRxOperatorToRetrunResponseObject(/*how?*/);
}
我实际上找到了一种通过以下方式实现它的方法:
public Observable<Response> prepareSomething() {
return api.requestSomthing()
.observeOn(Schedulers.io())
.flatMap(response -> {
ArrayList<Observable<Asset>> observables = new ArrayList<>();
for(Asset asset : response.getAssetsList()){
Observable downloadOb = Observable.just(asset)
.map(assetToDownload-> downloadAsset(assetToDownload, response.getSomeValue()));
observables.add(downloadOb);
}
return Observable.zip(observables, objects -> response);
});
}
但是看起来不太好。赞赏是否有人可以提供帮助。
答案 0 :(得分:1)
我会将下载逻辑嵌套到内部Observable
public Observable<Response> prepareSomething() {
return api.requestSomthing()
.observeOn(Schedulers.io())
.flatMap(response -> Observable.fromIterable(response.getAssetsList())
.flatMap( asset -> downloadAsset(asset))
.toList()
.flatMapObservable(downloadedAssets -> Observable.just(response))
);
}
您可以访问同一lambda中的响应和下载的资源