นากกายต่อท่อ async สองท่อนให้เป็นเส้นเดียวบนโต๊ะมิ้นต์

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