Every time my app starts, I need to call 2-3 URL endpoints to get the latest data from the API. Every app encounters this scenario one way or another. I need to know when each API call finishes so that I can prompt the user a Snackbar or dialog to indicate that I already got the latest data. And more importantly, I made sure that calling the function 2-3 times won’t block the main thread.
Here’s how I implemented it using Kotlin’s Coroutines.
My function structure looks like the one below. This function performs an HTTP GET from the API and saves it into a local database.
private suspend fun getDataFromAPI(url: String) = coroutineScope {
// More code
}
And this is how I called it using Coroutines.
CoroutineScope(Dispatchers.IO).launch {
val asyncData1 = async {
getDataFromAPI("https://someurl.com/api/data1")
}
val asyncData2 = async {
getDataFromAPI("https://someurl.com/api/data2")
}
val asyncData3 = async {
getDataFromAPI("https://someurl.com/api/data3")
}
if (asyncData1.await().join().responseMessage.isNotEmpty() &&
asyncData2.await().join().responseMessage.isNotEmpty() &&
asyncData3.await().join().responseMessage.isNotEmpty()
) {
// Display Snabackbar or dialog here
}
}
Important to take note here is the join() function which will wait for the completion of our async call.