Skip to content

Commit 10a33ce

Browse files
Simplify UseCase#3
1 parent 6341ac7 commit 10a33ce

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/usecases/coroutines/usecase3/PerformNetworkRequestsConcurrentlyViewModel.kt

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import androidx.lifecycle.viewModelScope
44
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
55
import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
66
import kotlinx.coroutines.async
7-
import kotlinx.coroutines.coroutineScope
7+
import kotlinx.coroutines.awaitAll
88
import kotlinx.coroutines.launch
99

1010
class PerformNetworkRequestsConcurrentlyViewModel(
@@ -30,6 +30,26 @@ class PerformNetworkRequestsConcurrentlyViewModel(
3030

3131
fun performNetworkRequestsConcurrently() {
3232
uiState.value = UiState.Loading
33+
34+
val oreoFeaturesDeferred = viewModelScope.async { mockApi.getAndroidVersionFeatures(27) }
35+
val pieFeaturesDeferred = viewModelScope.async { mockApi.getAndroidVersionFeatures(28) }
36+
val android10FeaturesDeferred =
37+
viewModelScope.async { mockApi.getAndroidVersionFeatures(29) }
38+
39+
viewModelScope.launch {
40+
try {
41+
val versionFeatures =
42+
awaitAll(oreoFeaturesDeferred, pieFeaturesDeferred, android10FeaturesDeferred)
43+
uiState.value = UiState.Success(versionFeatures)
44+
} catch (exception: Exception) {
45+
uiState.value = UiState.Error("Network Request failed")
46+
}
47+
}
48+
49+
/*
50+
51+
Alternatively:
52+
3353
viewModelScope.launch {
3454
try {
3555
// we need to wrap this code with a coroutineScope block
@@ -54,6 +74,6 @@ class PerformNetworkRequestsConcurrentlyViewModel(
5474
} catch (exception: Exception) {
5575
uiState.value = UiState.Error("Network Request failed")
5676
}
57-
}
77+
}*/
5878
}
5979
}

app/src/test/java/com/lukaslechner/coroutineusecasesonandroid/usecases/coroutines/usecase3/PerformNetworkRequestsConcurrentlyViewModelTest.kt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ class PerformNetworkRequestsConcurrentlyViewModelTest {
2424
private val receivedUiStates: MutableList<UiState> =
2525
arrayListOf()
2626

27-
28-
2927
@Test
3028
fun `performNetworkRequestsSequentially should return data after 3 times the response delay`() =
3129
coroutineTestRule.runBlockingTest {

0 commit comments

Comments
 (0)