https://kotlinlang.org logo
#android
Title
# android
a

ayush

10/01/2019, 2:46 AM
What's the best way to listen/observe to completion of multiple API calls in Kotlin? I know rxjava is an option , but is it possible to do something like this with coroutines ?
👌 1
g

gildor

10/01/2019, 2:49 AM
Depends on how this API call is implemented, if it’s suspend function, just use
async { suspendingApiCall() }
to run it in parallel and than List<Deferred<T>>.awaitAll() to get all results It’s covered in official coroutines guide
This is the simplest example. even without awaitAll(), just launch 2 async, and than call await(): https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html#concurrent-using-async
I also recommend you to check Coroutines and Channels introduction tour. Especially, Concurrency section of it: https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/05_Concurrency
a

ayush

10/01/2019, 12:45 PM
Thanks @gildor
I think async should work in my case
l

Lou Morda

10/01/2019, 4:30 PM
We do this with coroutines at my current job
a

ayush

10/02/2019, 3:54 AM
Can you share some more information about it, would like to know how you do it?
l

Lou Morda

10/02/2019, 6:41 PM
Launching 2 async, and then call await() is what we went with, essentially:
Copy code
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
            supervisorScope {
                val result1 = async { apiCall1() }.await()
                val result2 = async { apiCall2() }.await()
                Log.d("result", result1.toString() + result2.toString())
            }
        }
    }
    suspend fun apiCall1(): List<String> = listOf("1, 2, 3")
    suspend fun apiCall2(): List<String> = listOf("4, 5, 6")
g

gildor

10/03/2019, 10:12 AM
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch
This code is very bad style, even for sample. 1. You leak your scope, it’s not attached to any lifecycle. Because your example is Android Activity, just use
lifecycleScope
from AndroidX lifecycle-ktx and just do:
lifecycleScope.launch
2. There is no reason to use IO dispatcher here and in general with non-blocking suspend function 3. supervisorScope is redundant here, it’s needed only if you want to manage exception of every child coroutine manually, but usually not needed for parallel decomposition. So just remove it and’ use scope of
launch