Android: Sync multiple asynchronous network calls in Kotlin

Viewed 71

I have my network layer written in such a way that all the calls are made asynchronously using the Retrofit's call.enqueue(). I cannot change this implementation for several reasons, one being - it is written in Java.

Example:

repository.fetchUserData(object : NetworkListener<UserResponse> {
    override fun onSuccess(response: NetworkListener<UserResponse>?) {
    //back on UI thread
        userLiveData.value = response?.data
    }

    override fun onFailure(error: String) {
    //back on UI thread
        errorLiveData.value = error
    }
})

I am faced with a challenge of making several such network calls in parallel and show the data only when all of these calls are finished.

Using some boolean flags and tracking each network call finish, seems like a fragile solution.

Is there a better/simpler way to achieve this?

1 Answers

If you are using kotlin, it will be simpler way using async and await. If you want to continue to use Java, then you will have to use RxJava and combine the obeservales using merge or zip.

Related