Wie bekomme ich ein CompletableFuture<T> von einer Async-Http-Client-Anfrage?

Auf Async-Http-Client-Dokumentation ich sehen, wie man eine Future<Response> als das Ergebnis eines asynchronen HTTP-Get-Anfrage einfach tun, zum Beispiel:

AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
Future<Response> f = asyncHttpClient
      .prepareGet("http://api.football-data.org/v1/soccerseasons/398")
      .execute();
Response r = f.get();

Jedoch, für die Bequemlichkeit würde ich gerne eine CompletableFuture<T> statt, für die ich anwenden könnte eine Fortsetzung, die wandelt das Ergebnis in etwas anderes, zum Beispiel deserialisiert den Inhalt von Json in Java-Objekt (z.B. SoccerSeason.java). Dies ist, was ich tun möchte:

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);

Laut Async-Http-Client-Dokumentation der einzige Weg, dies zu tun ist durch eine AsyncCompletionHandler<T> Objekt und mit einem Versprechen. So baute ich eine Hilfs-Methode zu Ende:

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;
}

Mit dieser utility-Methode, die ich umschreiben kann das Vorherige Beispiel, nur tun:

getDataAsync("http://api.football-data.org/v1/soccerseasons/398")
    .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class))
    .thenAccept(System.out::println);

Gibt es einen besseren Weg, um eine CompletableFuture<T> aus einer Async-Http-Client-Anfrage?

Schreibe einen Kommentar