Java thenCompose: ต่อ Future แบบแบน ไม่ซ้อน CompletionStage
น้องกายEngineering
เรียก API แล้วขั้นสองคืน CompletableFuture อีกใบ ทำให้ได้ CompletableFuture<CompletableFuture<T>> ใช่ไหมครับ — ใช้ thenCompose เพื่อแบนเป็นชั้นเดียว
กฎสั้น ๆ:
thenApply= แปลงค่า → คืนค่าธรรมดาthenCompose= แปลงค่า → คืนCompletionStage/CompletableFutureอีกใบ
import java.util.concurrent.CompletableFuture;
public class Main {
static CompletableFuture<Integer> parseAsync(String raw) {
return CompletableFuture.supplyAsync(() -> Integer.parseInt(raw));
}
static CompletableFuture<Integer> doubleAsync(int n) {
return CompletableFuture.supplyAsync(() -> n * 2);
}
public static void main(String[] args) throws Exception {
Integer result = parseAsync("21")
.thenCompose(Main::doubleAsync)
.get();
assert result == 42 : result;
System.out.println("ok");
}
}
Recap
- เปลี่ยน
thenApply(x -> otherAsync(x))เป็นthenComposeเมื่อฟังก์ชันคืน Future - เก็บ error handling ด้วย
handle/exceptionallyที่ขอบบริการ - อ่านJavadoc thenCompose