我发现下面的代码(为简洁起见进行了修改),这是有问题的,据我所知存在缺陷。
通常不建议使用toBlocking(),它已在反应式上下文中使用
它返回single();因此,一旦它从流中获取了单个项目,它便终止了它,而忽略了其他不希望的项目。
虽然我相信我可以解决此问题,但可以通过将single
删除为last
吗?有人可以解释一下,我该如何删除toBlocking()
的使用?
observableList.map(incentiveDetailsList -> {
List<SomeObject> list = mapThisList(incentiveDetailsList);
return Observable.just(list)
.flatMap(Observable::from)
.flatMap(item -> {
Request request = createRequest(item);
String accountNumber = item.getAccountNumber();
return serviceThatReturnsObservable.load(request)
.doOnError(onError -> {
Observable.error(new Exception("some context"));
})
.map(response -> {
handleError(response);
return responseMap.put(accountNumber, buildResponse(response.getResponse()));
});
})
.map(resp -> mapResponse(store, incentiveDetailsList, responseMap))
.toBlocking()
.single();
})
最佳答案
您可以将map + toBlocking替换为flatMap
(或concatMap
):
observableList.flatMap(incentiveDetailsList -> {
List<SomeObject> list = mapThisList(incentiveDetailsList);
return Observable.from(list)
.flatMap(item -> {
Request request = createRequest(item);
String accountNumber = item.getAccountNumber();
return serviceThatReturnsObservable.load(request)
/* this has no effect:
.doOnError(onError -> {
Observable.error(new Exception("some context"));
})
*/
.map(response -> {
handleError(response);
return responseMap.put(accountNumber,
buildResponse(response.getResponse()));
});
})
.map(resp -> mapResponse(store, incentiveDetailsList, responseMap));
})