Junior — Middle
How can you implement concurrent execution of multiple tasks using coroutines?
sobes.tech AI
Answer from AI
To perform multiple tasks simultaneously using coroutines in Kotlin, you can use:
launch— starts a new coroutine that runs concurrently with others.async— starts a coroutine that returns a result viaDeferred.
Example of running two tasks concurrently and waiting for their results:
import kotlinx.coroutines.*
fun main() = runBlocking {
val job1 = async {
delay(1000)
"Result of task 1"
}
val job2 = async {
delay(500)
"Result of task 2"
}
// Wait for both results
val result1 = job1.await()
val result2 = job2.await()
println(result1)
println(result2)
}
Thus, coroutines make it easy to run multiple tasks in parallel and synchronize their results.