ayush
10/01/2019, 2:46 AMgildor
10/01/2019, 2:49 AMasync { suspendingApiCall() }
to run it in parallel and than List<Deferred<T>>.awaitAll() to get all results
It’s covered in official coroutines guidegildor
10/01/2019, 2:51 AMgildor
10/01/2019, 2:53 AMayush
10/01/2019, 12:45 PMayush
10/01/2019, 12:45 PMLou Morda
10/01/2019, 4:30 PMayush
10/02/2019, 3:54 AMLou Morda
10/02/2019, 6:41 PMoverride 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")
gildor
10/03/2019, 10:12 AMCoroutineScope(<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