How to get CompletableFuture <T> from an Async Http client request?
In the Async Http Client Documentation, I see how to get Future<Response> as a result of an asynchronous HTTP Get request, just doing, for example:
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(); Future<Response> f = asyncHttpClient .prepareGet("http://api.football-data.org/v1/soccerseasons/398") .execute(); Response r = f.get(); However, for convenience, I would like to get a CompletableFuture<T> instead, for which I could apply a continuation that converts the result to something else, for example deserializing the contents of the response from Json to a Java object (e.g. SoccerSeason.java ). This is what I would like to do:
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(); CompletableFuture<Response> f = asyncHttpClient .prepareGet("http://api.football-data.org/v1/soccerseasons/398") .execute(); f .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class)) .thenAccept(System.out::println); According to the Async Http Client Documentation, the only way to do this is through the AsyncCompletionHandler<T> object and use the promise. Therefore, I built a helper method for this purpose:
CompletableFuture<Response> getDataAsync(String path){ CompletableFuture<Response> promise = new CompletableFuture<>(); asyncHttpClient .prepareGet(path) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { promise.complete(response); return response; } @Override public void onThrowable(Throwable t) { promise.completeExceptionally(t); } }); return promise; } Using this utility method, I can rewrite the previous example:
getDataAsync("http://api.football-data.org/v1/soccerseasons/398") .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class)) .thenAccept(System.out::println); Is there a better way to get CompletableFuture<T> from an Async Http client request?