美文网首页
thenApply()和thenCompose()的区别

thenApply()和thenCompose()的区别

作者: 加一片柠檬233 | 来源:发表于2019-03-15 11:01 被阅读0次
  1. thenapply()是接受一个Function<? super T,? extends U>参数用来转换CompletableFuture,相当于流的map操作,返回的是非CompletableFuture类型,它的功能相当于将CompletableFuture<T>转换成CompletableFuture<U>。
    thenApply()源码:
 public <U> CompletableFuture<U> thenApply(
    Function<? super T,? extends U> fn) {
        return uniApplyStage(null, fn);
   }

解读:
参数: Function<? super T,? extends U> fn)
输入前面的CompletableFuture<T>中的T的值,返回一个继承U的类型的值,将这个值返回
顺序:先确定返回值U或其子类,再确定方法中 public <U> CompletableFuture<U> thenApply()中的 <U>类型

  1. thenCompose()在异步操作完成的时候对异步操作的结果进行一些操作,并且仍然返回CompletableFuture类型,相当于flatMap,用来连接两个CompletableFuture。

总结:thenApply()转换的是泛型中的类型,是同一个CompletableFuture;
thenCompose()用来连接两个CompletableFuture,是生成一个新的CompletableFuture。他们都是让CompletableFuture可以对返回的结果进行后续操作,就像流一样进行map和flatMap的装换。

  1. 例子:
    thenApply():
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
      return 100;
});
CompletableFuture<String> f = future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString());

System.out.println(f.get()); //"1000"

thenCompose():

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    return 100;
});
CompletableFuture<String> f = future.thenCompose( i -> {
    return CompletableFuture.supplyAsync(() -> {
        return (i * 10) + "";
    });
});

System.out.println(f.get()); //1000

相关文章

网友评论

      本文标题:thenApply()和thenCompose()的区别

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