0
0
Kotlinprogramming~3 mins

Why Async and await for concurrent results in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could do many things at once and finish faster without extra effort?

The Scenario

Imagine you need to fetch data from three different websites one after another. You write code that waits for the first website to respond before moving to the second, then the third. This makes your program slow and boring, like waiting in three long lines one by one.

The Problem

Doing tasks one by one wastes time because your program sits idle waiting for each task to finish. It's like standing in line at a coffee shop three times instead of ordering all drinks at once. Also, it's easy to make mistakes managing all these waiting steps manually.

The Solution

Using async and await lets your program start all tasks at the same time and then wait for all results together. It's like ordering all your drinks at once and picking them up when ready. This saves time and keeps your code clean and easy to understand.

Before vs After
Before
val result1 = fetchData1()
val result2 = fetchData2()
val result3 = fetchData3()
After
val deferred1 = async { fetchData1() }
val deferred2 = async { fetchData2() }
val deferred3 = async { fetchData3() }
val result1 = deferred1.await()
val result2 = deferred2.await()
val result3 = deferred3.await()
What It Enables

You can run many tasks at the same time and get all results faster, making your apps quicker and more responsive.

Real Life Example

Imagine a weather app that fetches temperature, humidity, and wind speed from different servers. Using async and await, it gets all data together quickly, so you see the full weather report without waiting long.

Key Takeaways

Manual waiting slows down programs and is error-prone.

Async and await let tasks run together, saving time.

This makes code cleaner and apps faster.