- thenapply()是接受一個(gè)Function<? super T,? extends U>參數(shù)用來轉(zhuǎn)換CompletableFuture,相當(dāng)于流的map操作,返回的是非CompletableFuture類型,它的功能相當(dāng)于將CompletableFuture<T>轉(zhuǎn)換成CompletableFuture<U>俊庇。
thenApply()源碼:
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
解讀:
參數(shù): Function<? super T,? extends U> fn)
輸入前面的CompletableFuture<T>中的T的值店乐,返回一個(gè)繼承U的類型的值废离,將這個(gè)值返回
順序:先確定返回值U或其子類献汗,再確定方法中 public <U> CompletableFuture<U> thenApply()中的 <U>類型
- thenCompose()在異步操作完成的時(shí)候?qū)Ξ惒讲僮鞯慕Y(jié)果進(jìn)行一些操作敢订,并且仍然返回CompletableFuture類型,相當(dāng)于flatMap罢吃,用來連接兩個(gè)CompletableFuture。
總結(jié):thenApply()轉(zhuǎn)換的是泛型中的類型昭齐,是同一個(gè)CompletableFuture尿招;
thenCompose()用來連接兩個(gè)CompletableFuture,是生成一個(gè)新的CompletableFuture阱驾。他們都是讓CompletableFuture可以對(duì)返回的結(jié)果進(jìn)行后續(xù)操作就谜,就像流一樣進(jìn)行map和flatMap的裝換。
- 例子:
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