Junior — Middle
How do you organize parallel execution of operations inside a suspend function in Kotlin?
sobes.tech AI
Answer from AI
To perform parallel operations inside a suspend function in Kotlin, coroutines and the async function combined with await are typically used. This allows multiple asynchronous tasks to run concurrently and then wait for their completion.
Example:
suspend fun fetchData(): List<String> = coroutineScope {
val deferred1 = async { fetchFromNetwork1() }
val deferred2 = async { fetchFromNetwork2() }
val result1 = deferred1.await()
val result2 = deferred2.await()
listOf(result1, result2)
}
Here, async launches tasks in parallel, and await waits for their completion. It is important to use coroutineScope or supervisorScope for proper coroutine lifecycle management inside a suspend function.