抽象的想法
我希望从一组Futures中获得第一个值,它满足给定的谓词。
如果找到满意的价值,则应取消所有其他期货。如果在所有Futures返回后没有找到任何值,则应终止执行(通过返回默认值或抛出异常)。
具体示例
public boolean isThereVacantHotelRooms(Set<URL> hotelApiUrls) {
// returns true if any provided server responds with a number larger than 0
}
我正在寻找一种在Java 8中实现上述功能的漂亮方式(外部库很好)。我已经尝试用 CompletableFuture 以及RxJava实现它,但是我觉得这个问题非常惯用,我最终得到了很多丑陋的代码。
答案 0 :(得分:3)
我认为,您的案例可以通过合并,过滤和结合来实现:
List<Observable<HotelInfo>> hotels = new ArrayList<>();
for (URL u : urls) {
Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u);
hotels.add(hotelInfo);
}
Observable.merge(hotels)
.filter(h -> h.vacancy > 0)
.take(1)
.subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace);
答案 1 :(得分:2)
由于您尝试了其他解决方案,因此这里是bayou解决方案进行比较
// throw exception for failure
public void checkVacantHotelRooms(Set<URL> hotelApiUrls) throws Exception
{
checkVacantHotelRoomsAsync(hotelApiUrls) // Async<Void>
.timeout(Duration.ofSeconds(10)) // cancel on 10s
.sync(); // async -> sync
}
public Async<Void> checkVacantHotelRoomsAsync(Set<URL> hotelApiUrls)
{
Stream<Async<Void>> resultStream = hotelApiUrls.stream() // Stream<URL>
.map(this::getResponseBodyAsync) // Stream<Async<String>>
.map(asyncBody->asyncBody.map(this::checkResponse)); // Stream<Async<Void>
return AsyncBundle.anyOf(resultStream);
// succeeds if one result succeeds; others will be cancelled
}
Void checkResponse(String responseBody) throws Exception
{
if(responseBody.contains("something"))
return (Void)null;
throw new Exception("none in this hotel");
}
-----
HttpClient httpClient = new HttpClient();
int maxBodyLength = 1000;
Async<String> getResponseBodyAsync(URL url)
{
Async<HttpResponse> asyncResponse = httpClient.doGet(url.toExternalForm());
return asyncResponse.then(resp->resp.bodyString(maxBodyLength));
}