Skip to content

Commit db07bd3

Browse files
Add alternative implementation of UseCae#5 "Network request with timeout"
1 parent 10a33ce commit db07bd3

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/usecases/coroutines/usecase5/NetworkRequestWithTimeoutViewModel.kt

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,49 @@ import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
66
import kotlinx.coroutines.TimeoutCancellationException
77
import kotlinx.coroutines.launch
88
import kotlinx.coroutines.withTimeout
9+
import kotlinx.coroutines.withTimeoutOrNull
910

1011
class NetworkRequestWithTimeoutViewModel(
1112
private val api: MockApi = mockApi()
1213
) : BaseViewModel<UiState>() {
1314

14-
fun performNetworkRequest(timeOut: Long) {
15+
fun performNetworkRequest(timeout: Long) {
1516
uiState.value = UiState.Loading
17+
// usingWithTimeout(timeout)
18+
usingWithTimeoutOrNull(timeout)
19+
}
20+
21+
private fun usingWithTimeout(timeout: Long) {
1622
viewModelScope.launch {
1723
try {
18-
withTimeout(timeOut) {
19-
val recentVersions = api.getRecentAndroidVersions()
20-
uiState.value = UiState.Success(recentVersions)
24+
val recentVersions = withTimeout(timeout) {
25+
api.getRecentAndroidVersions()
2126
}
27+
uiState.value = UiState.Success(recentVersions)
2228
} catch (timeoutCancellationException: TimeoutCancellationException) {
2329
uiState.value = UiState.Error("Network Request timed out!")
2430
} catch (exception: Exception) {
2531
uiState.value = UiState.Error("Network Request failed!")
2632
}
2733
}
2834
}
35+
36+
private fun usingWithTimeoutOrNull(timeout: Long) {
37+
viewModelScope.launch {
38+
try {
39+
val recentVersions = withTimeoutOrNull(timeout) {
40+
api.getRecentAndroidVersions()
41+
}
42+
43+
if (recentVersions != null) {
44+
uiState.value = UiState.Success(recentVersions)
45+
} else {
46+
uiState.value = UiState.Error("Network Request timed out!")
47+
}
48+
} catch (exception: Exception) {
49+
uiState.value = UiState.Error("Network Request failed!")
50+
}
51+
}
52+
}
53+
2954
}

0 commit comments

Comments
 (0)