美文网首页
thenApply()和thenCompose()的异同

thenApply()和thenCompose()的异同

作者: FoxLayla | 来源:发表于2019-03-05 17:34 被阅读0次

thenApply()和thenCompose()的异同

相同之处

thenApply()themCompose()都是用于连接多个CompletableFuture调用,通过类似于流的操作来处理CompletableFutrue的结果

不同之处

  • thenApply()接收一个函数作为参数,使用该函数处理上一个CompletableFuture调用的结果,并返回一个具有处理结果的Future对象

    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenApply(string -> string + " world");
    
    try {
        System.out.println(completableFuture.get());
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    

    可以看到thenApply()适用于对CompletableFuture调用的结果进行一些转换。

  • thenCompose()的参数为一个返回CompletableFuture实例的函数,该函数的参数是先前计算步骤的结果

    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(string -> CompletableFuture.supplyAsync(() -> string + " world"));
            
    try {
        System.out.println(completableFuture.get());
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    

    可以看到thenCompose()会将内部的CompletableFuture调用展开来并使用上一个CompletableFutre调用的结果在下一步的CompletableFuture调用中进行运算,因此thenCompose()更适用于多个CompletableFuture调用的连接。


    参考

相关文章

网友评论

      本文标题:thenApply()和thenCompose()的异同

      本文链接:https://www.haomeiwen.com/subject/ibvouqtx.html