I am new to Kotlin and coroutines.
I have the below code:
fun asyncCallForRelationIdList(relationIds: List<String>): List<Any?> = runBlocking {
println("Starting asynchronous code flow")
asyncCallForUserIdList(relationIds)
}
suspend fun asyncCallForUserIdList(userIds: List<String>): List<Any?> = coroutineScope {
println("Elements in list are supposed to call api concurrently")
val listval = mutableListOf<Any?>()
val result0 = async {restApiCall(relationId = userIds[0])}
val result1 = async {restApiCall(relationId = userIds[1])}
listval.add(result0.await())
listval.add(result1.await())
listval.toList()
}
suspend fun restApiCall(relationId: String): Any? {
println("api call... the api will timeout with an artificial delay")
//api call
//return "api result"
}
asyncCallForRelationIdList()
function will call asyncCallForUserIdList()
which then makes an API call that will timeout.
My question is about the async
keyword that I am using in coroutineScope
. I expect the 2 async calls to happen concurrently. But that is not the case here. After the first api call, the thread waits for the service to timeout instead of making the 2nd api call concurrently. Why?