java多嵌套CompletionStage相当于“flatMap”?

时间:2016-03-30 11:26:17

标签: java future completable-future

所以考虑到我有以下例子:

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

});

我的问题在于整个CompletionStage<CompletionStage<CompletionStage<CompletionStage<Boolean>>>>多嵌套未来类型。是否可以通过在Scala中使用类似CompletionStage<Boolean>的内容将其缩减为flatMap,还是有其他方法可以执行此操作?

1 个答案:

答案 0 :(得分:11)

是的,您正在寻找thenCompose(fn)操作:

  

返回一个新的CompletionStage,当这个阶段正常完成时,将以此阶段作为所提供函数的参数执行。

此方法将一个函数作为参数,该参数获取此完成阶段的结果并返回另一个完成阶段。

因此,您可以拥有以下内容:

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

});