Video tayyorlanmoqda

CompletableFuture'da thenApply, thenCompose va thenCombine qanday farq qiladi?

thenApply natijani oddiy funksiya bilan o'zgartiradi. thenCompose keyingi qadam o'zi CompletableFuture qaytarganda ishlatiladi va ichma-ich future'ni "yassilaydi". thenCombine ikki mustaqil future'ning natijasini birlashtiradi.

📖 Javob

Stream'dagi map va flatMap'ga o'xshatish oson:

CompletableFuture<User> userF = userClient.findAsync(id);

// thenApply — sinxron o'zgartirish (map)
CompletableFuture<String> nameF = userF.thenApply(User::fullName);

// thenCompose — keyingi qadam ham async (flatMap)
CompletableFuture<List<Order>> ordersF =
        userF.thenCompose(u -> orderClient.findByUserAsync(u.id()));

// thenApply bilan yozilsa tip noqulay bo'ladi:
// CompletableFuture<CompletableFuture<List<Order>>>

// thenCombine — ikkita parallel so'rov
CompletableFuture<Profile> profileF = userF.thenCombine(
        balanceClient.getAsync(id),
        (user, balance) -> new Profile(user, balance));

thenCombine'da ikkala so'rov bir vaqtda ketadi — ketma-ket thenCompose qilganda umumiy vaqt yig'iladi, bu yerda esa eng uzunining vaqti olinadi. Ikkitadan ko'p future uchun CompletableFuture.allOf(...) bor, keyin har biridan join() bilan natija olinadi.

Async qo'shimchali variantlar (thenApplyAsync) qadamni boshqa thread'da bajaradi. Executor bermasangiz, ForkJoinPool.commonPool() ishlatiladi — bloklaydigan I/O uchun o'z executor'ingizni bering.