我有以下要求:查询外部服务器,以便将结果通知给rest控制器,同时将其保存到mongo。问题是,在以下实现中,当发生mongo错误时,结果不会返回到rest控制器。有什么办法可以将两个调用与rxJAva分离?
public Observable<LowestFareByProvider> lowestFareByProvider(final
FlightSearchRequest flightSearchRequest) {
final FlightSpecification flightSpecification = FlightSpecification.builder()
.from(flightSearchRequest.getFrom())
.to(flightSearchRequest.getTo())
.departure(flightSearchRequest.getDeparture())
.build();
return flightService.lowestFareByProvider(flightSpecification, flightSearchRequest.getProviders())
.map(it -> {
logger.debug("Saving to db in thread: {}", Thread.currentThread().getName());
return lowestFareByProviderRepository.save(it);
})
.flatMap(Single::toObservable);
}
答案 0 :(得分:1)
当Mongo保存呼叫失败并将结果转发给订户时,您似乎想吃掉错误。
public Observable<LowestFareByProvider> lowestFareByProvider(final
FlightSearchRequest flightSearchRequest) {
final FlightSpecification flightSpecification = FlightSpecification.builder()
.from(flightSearchRequest.getFrom())
.to(flightSearchRequest.getTo())
.departure(flightSearchRequest.getDeparture())
.build();
return flightService.lowestFareByProvider(flightSpecification, flightSearchRequest.getProviders())
.flatMap(result -> {
logger.debug("Saving to db in thread: {}", Thread.currentThread().getName());
return Observable.fromCallable(() -> { lowestFareByProviderRepository.save(result)})
.onErrorReturn(result);
});
请检查语法。在这里,onErrorReturn
忽略来自Mongo保存调用(如果有)的错误,并将结果转发回订阅者。在您现阶段拥有Single::toObservable
的情况下,我删除了Observable
。