So considering I have the following example:
CompletionStage<String> tokenFuture = getToken();
CompletionStage<CompletionStage<CompletionStage<CompletionStage<Boolean>>>> result = tokenFuture.thenApply(token -> {
WSRequest request = ws.url(url).setHeader("Authorization", "Bearer " + token);
CompletionStage<WSResponse> response = request.post(json);
return response.thenApply(r -> {
if (r.getStatus() == 201) {
return CompletableFuture.supplyAsync(() -> CompletableFuture.supplyAsync(() -> true));
} else {
return getToken().thenApply(t -> {
WSRequest req = ws.url(url).setHeader("Authorization", "Bearer " + t);
return req.post(json).thenApply(b -> b.getStatus() == 201);
});
}
});
});
My problem is with the whole CompletionStage<CompletionStage<CompletionStage<CompletionStage<Boolean>>>>
multi nested future type. Is it possible to reduce it to just CompletionStage<Boolean>
by using something like flatMap
in Scala or is there another way to do this?
Yes, you are looking for the thenCompose(fn)
operation:
Returns a new CompletionStage that, when this stage completes normally, is executed with this stage as the argument to the supplied function.
This method takes a function as parameter that takes the result of this completion stage and returns another completion stage.
As such, you could have the following:
CompletionStage<String> tokenFuture = getToken();
CompletionStage<Boolean> result = tokenFuture.thenCompose(token -> {
WSRequest request = ws.url(url).setHeader("Authorization", "Bearer " + token);
CompletionStage<WSResponse> response = request.post(json);
return response.thenCompose(r -> {
if (r.getStatus() == 201) {
return CompletableFuture.supplyAsync(() -> true);
} else {
return getToken().thenCompose(t -> {
WSRequest req = ws.url(url).setHeader("Authorization", "Bearer " + t);
return req.post(json).thenApply(b -> b.getStatus() == 201);
});
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With