Open In App

Parallel Multiple Network Calls Using Kotlin Coroutines

Improve
Improve
Like Article
Like
Save
Share
Report

Application’s home screen is where we need to populate multiple views like Promotional banners, List to show core content of the app, Basic user info, etc., It is really easy to fill all these views with data when you get all the required data in a single API call, but that’s, not the case every time. Many times we need to call multiple API requests to get the required data on client devices and wait for all of them to execute one after the other, fetch the result, and process it. We are going to learn how to make Parallel Multiple Network Calls Using Kotlin Coroutines. We have learned to write the code inside the ViewModel with Kotlin Coroutines and LiveData that follows a basic MVVM Architecture. This tutorial will also help you in doing any type of background tasks in parallel using Kotlin Coroutines. 

And Yes the Progress view is still Spinning in the home screen, So how about we take down the spinner much earlier than before by executing the API requests in parallel let us look at the code first.

Kotlin




class HomeViewModel(val homeDataUsecase: HomeDataUsecase
):BaseViewModel() {
    fun getAllData() {
        viewModelScope.launch {
            coroutineScope {
               val bannerResponse:BaseResponse<Bannerdata>?
               val contentResponse: BaseResponse<ContentData>?
               val userResponse: BaseResponse<Userdata>?
               val call1 = async { homeDataUsecase.getBannerdata()}
               val call2 = async { homeDataUsecase.getContentData()}
               val call3 = async { homeDataUsecase.getUserdata() }
               try {
                    bannerResponse = call1.await()
                    contentResponse = call2.await()
                    userResponse = call3.await()
                   } catch (ex: Exception) {
                    ex.printStackTrace()
                   
          processData(bannerResponse, contentResponse, userResponse)
            }
        }
    }


When you have to make different API calls and wait, you do something like this:

Kotlin




viewModelScope.launch {
   withContext(dispatcherProvider.heavyTasks) {
       val apiResponse1 = api.get1() // suspend function
       val apiResponse2 = api.get2() // suspend function
       if (apiResponse1.isSuccessful() && apiResponse2.isSuccessful() { .. }
   }
}


but what happens if I’ve to do multiple concurrent same API Calls with different parameters:

Kotlin




viewModelScope.launch {
   withContext(dispatcherProvider.heavyTasks) {
       val multipleIds = listOf(1, 2, 3, 4, 5, ..)
       val content = arrayListOf<CustomObj>()
       multipleIds.forEach { id ->
             // suspend function
            val apiResponse1 = api.get1(id) 
            if (apiResponse1.isSuccessful()) {
                content.find { it.id == id }.enable = true
            }
       }
       liveData.postValue(content)
   }
}


The problem with the second approach is that it will go through all ids of multiple lists and make async calls, but the content will be posted probably before that. How can I wait for all the responses for each loop to be finished and only then postValue of the content to view? so yeah, that’s the basic idea about Parallel Multiple Network Calls Using Kotlin Coroutines



Last Updated : 03 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads