Careeroza
Real World Example
Flipkart Checkout: All or Nothing
At checkout, the app must reserve stock and charge the payment. If payment fails, the stock reservation must be cancelled and released. coroutineScope gives exactly this: one failure cancels the sibling, and a finally block does the cleanup.
checkout() coroutineScope ├─ launch reserveStock() ── cancelled ──► finally: release stock └─ launch chargePayment() ── FAILS (card declined) → exception reaches checkout(), user sees "Payment failed"
Code
Example
import kotlinx.coroutines.*
class PaymentException(msg: String) : Exception(msg)
suspend fun reserveStock(sku: String) {
println("Reserving $sku...")
try {
delay(500)
println("Reserved $sku")
} catch (e: CancellationException) {
println("Released reservation for $sku")
throw e
}
}
suspend fun chargePayment(amount: Int, card: String) {
delay(200)
if (card.endsWith("0000")) throw PaymentException("Card declined for Rs $amount")
println("Charged Rs $amount")
}
suspend fun checkout(sku: String, amount: Int, card: String): String = try {
coroutineScope {
launch { reserveStock(sku) }
launch { chargePayment(amount, card) }
}
"Order confirmed"
} catch (e: PaymentException) {
"Payment failed: ${e.message}"
}
fun main() = runBlocking {
println(checkout("PHONE-128GB", 15999, "4111-1111-1111-1111"))
println("---")
println(checkout("LAPTOP-16GB", 54999, "4000-0000-0000-0000"))
}Output
Reserving PHONE-128GB... Charged Rs 15999 Reserved PHONE-128GB Order confirmed --- Reserving LAPTOP-16GB... Released reservation for LAPTOP-16GB Payment failed: Card declined for Rs 54999