Middle
How to run two network requests simultaneously using Coroutine in Kotlin?
sobes.tech AI
Answer from AI
To run two network requests concurrently using coroutines in Kotlin, you can use async.
import kotlinx.coroutines.*
suspend fun fetchUserData(): String {
delay(1000) // Simulate network request
return "User Data"
}
suspend fun fetchItems(): String {
delay(1500) // Simulate network request
return "Items Data"
}
suspend fun performConcurrentRequests() = coroutineScope {
val userDataDeferred: Deferred<String> = async { fetchUserData() }
val itemsDataDeferred: Deferred<String> = async { fetchItems() }
val userData = userDataDeferred.await()
val itemsData = itemsDataDeferred.await()
println("User Data: $userData")
println("Items Data: $itemsData")
}
fun main() = runBlocking {
performConcurrentRequests()
}
asynclaunches a new process in a parallel coroutine and returns aDeferred, which is a lightweight non-blocking future.await()suspends execution until the corresponding coroutine completes and returns its result.coroutineScopecreates a scope in which all child coroutines are canceled if any of them fails.runBlockingis used here to run a blockingmainfunction in a coroutine, allowing suspend functions to be called. In a real Android app, other dispatchers and scopes (e.g.,ViewModelScope,LifecycleScope) are often used to launch coroutines.