Skip to content

Variable number of network requests

Devrath edited this page Jun 15, 2021 · 1 revision
  • Demonstrates the simple usage of map() to perform a dynamic amount of network requests.
  • At first, this use case performs a network request to load all Android versions.
  • Then it performs a network request for each Android version to load its features.
  • It contains an implementation that performs the network requests sequentially and another one that performs them concurrently.
class VariableAmountOfNetworkRequestsViewModel(
    private val mockApi: MockApi = mockApi()
) : BaseViewModel<UiState>() {

    fun performNetworkRequestsSequentially() {
        uiState.value = UiState.Loading
        viewModelScope.launch {
            try {
                val recentVersions = mockApi.getRecentAndroidVersions()
                val versionFeatures = recentVersions.map { androidVersion ->
                    mockApi.getAndroidVersionFeatures(androidVersion.apiLevel)
                }
                uiState.value = UiState.Success(versionFeatures)
            } catch (exception: Exception) {
                uiState.value = UiState.Error("Network Request failed")
            }
        }
    }

    fun performNetworkRequestsConcurrently() {
        uiState.value = UiState.Loading
        viewModelScope.launch {
            try {
                val recentVersions = mockApi.getRecentAndroidVersions()
                val versionFeatures = recentVersions
                    .map { androidVersion ->
                        async { mockApi.getAndroidVersionFeatures(androidVersion.apiLevel) }
                    }.awaitAll()
                uiState.value = UiState.Success(versionFeatures)
            } catch (exception: Exception) {
                uiState.value = UiState.Error("Network Request failed")
            }
        }
    }
}
Clone this wiki locally