Questions
Answer
Managing execution order is a core strength of Coroutines.
Series Execution (Sequential)
By default, code inside a coroutine runs sequentially. Each suspending function waits for the previous one to finish.
```kotlin launch { val data = fetchData() // Suspends until finished processData(data) // Runs after fetchData } ```
Parallel Execution (Concurrent)
To run tasks at the same time, use `async`.
Using `async` / `await`
`async` starts a coroutine and returns a `Deferred` result. Calling `await()` suspends until the result is ready.
```kotlin launch { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() }
// Both run in parallel here
println("The answer is \${one.await() + two.await()}")
}
} ```
Using `join`
If you don't need a result but want to wait for jobs to complete:
```kotlin val job1 = launch { ... } val job2 = launch { ... }
joinAll(job1, job2) // Wait for both to finish ```
Accelerate Your Growth
Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.