Learn By Doing : Executing a list of Retrofit requests Asynchronously using Coroutines on Android.
Prerequisites —Basic knowledge of Coroutines. You can use this guide for help.
The Synchronous Approach
I use val dogBreedList = api.getBreedsList().message.keys.toList()
to fetch all the breeds and convert it into a List.
This happens in background thread ,Dispatcher.IO
as explained in Part 1 because of the suspend
modifier in retrofit requests in MainActivityApi.kt.
After fetching the breeds, for each breed api.getImageByUrl(it).message
is called and then waited on until a result in returned after which the same api is called for another breed.
This happens for about 50 breeds Synchronously, and takes over 30 Seconds.
The Asynchronous Approach
Instead of loading images one by one for every breed synchronously, we can run all the api requests asynchronously, this should reduce the time considerably.
In MainActivityApi.kt, remove ❌ the suspend
modifier from fun getImageByUrlAsync()
as I’ll use async{}
and await()
, while manually switching threads.
In MainActivityRepositoryImpl.kt, replace code with above code.
For every breed in the list, I run
async { api.getImageByUrl(it) }
This fetches images asynchronously for all the breeds and then call .awaitAll()
which suspends the function until all the api calls have been executed and results returned.
Once that’s done, run this for every returned result.
forEach {
list.add(Dog(extractBreedName(it.message), it.message))
}
That’s it! ✅
The execution time reduces to 1/5 of the time needed in synchronous requests.
You can find the code for this tutorial here
Cleaner Code 🧹
Use this extension function to make your code a little cleaner.
And use it like this.