LukasLechnerDev / Kotlin-Coroutines-and-Flow-UseCases-on-Android

🎓 Learning Kotlin Coroutines and Flows for Android by example. 🚀 Sample implementations for real-world Android use cases. 🛠 Unit tests included!
Apache License 2.0
2.63k stars 433 forks source link

Perform several network requests concurrently #3

Closed ahhsfj1991 closed 4 years ago

ahhsfj1991 commented 4 years ago
coroutineScope {
                    val oreoFeaturesDeferred = async { mockApi.getAndroidVersionFeatures(27) }
                    val pieFeaturesDeferred = async { mockApi.getAndroidVersionFeatures(28) }
                    val android10FeaturesDeferred = async { mockApi.getAndroidVersionFeatures(29) }

                    val oreoFeatures = oreoFeaturesDeferred.await()
                    val pieFeatures = pieFeaturesDeferred.await()
                    val android10Features = android10FeaturesDeferred.await()

                    val versionFeatures = listOf(oreoFeatures, pieFeatures, android10Features)

                    // other alternative: (but slightly different behavior when a deferred fails, see docs)
                    // val versionFeatures = awaitAll(oreoFeaturesDeferred, pieFeaturesDeferred, android10FeaturesDeferred)

                    uiState.value = UiState.Success(versionFeatures)
                }

i have some question about this code, deferred's await() function will suspend this coroutines, so this demo code can't performed in parallel

LukasLechnerDev commented 4 years ago

Hi! Yes .await() will suspend the parent coroutine, but the child coroutines started with async{} will keep running concurrently.