Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java multi nested CompletionStage equivalent to "flatMap"?

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?

like image 754
Caballero Avatar asked Mar 30 '16 11:03

Caballero


1 Answers

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

});
like image 143
Tunaki Avatar answered Oct 22 '22 08:10

Tunaki