1

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?

firstpostcommenter
  • 2,328
  • 4
  • 30
  • 59
  • https://stackoverflow.com/questions/55664109/is-there-asyncall-and-or-awaitall-operators-for-kotlin-coroutines – firstpostcommenter Mar 11 '22 at 19:56
  • https://www.geeksforgeeks.org/launch-vs-async-in-kotlin-coroutines, https://stackoverflow.com/questions/46226518/what-is-the-difference-between-launch-join-and-async-await-in-kotlin-coroutines – firstpostcommenter Mar 11 '22 at 20:27
  • 1
    Change your async calls to `async(Dispatchers.IO) { ... }` because they're not actually asynchronous, currently they're running in the scope of `runBlocking`. – Pawel Mar 11 '22 at 20:40
  • How is your `restApiCall()` implemented? Your example should work as you expect, in parallel. But only assuming that `restApiCall()` was implemented properly, so it doesn't block the thread. If it blocks (my guess) then you need to fix its implementation to make it suspend instead. – broot Mar 11 '22 at 23:59
  • @Pawel Yes this has solved the issue. Thanks. – firstpostcommenter Mar 12 '22 at 07:43
  • https://developer.android.com/kotlin/coroutines/coroutines-adv – firstpostcommenter Mar 12 '22 at 07:44

2 Answers2

0

you are using runBlocking so its will block the main thread and run one by one. and its not Starting asynchronous code flow.

vignesh
  • 492
  • 3
  • 9
0

Change your async calls to async(Dispatchers.IO) { ... } because they're not actually asynchronous, currently they're running in the scope of runBlocking

Thanks to @Pawel

firstpostcommenter
  • 2,328
  • 4
  • 30
  • 59