@@ -6,24 +6,49 @@ import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
6
6
import kotlinx.coroutines.TimeoutCancellationException
7
7
import kotlinx.coroutines.launch
8
8
import kotlinx.coroutines.withTimeout
9
+ import kotlinx.coroutines.withTimeoutOrNull
9
10
10
11
class NetworkRequestWithTimeoutViewModel (
11
12
private val api : MockApi = mockApi()
12
13
) : BaseViewModel<UiState>() {
13
14
14
- fun performNetworkRequest (timeOut : Long ) {
15
+ fun performNetworkRequest (timeout : Long ) {
15
16
uiState.value = UiState .Loading
17
+ // usingWithTimeout(timeout)
18
+ usingWithTimeoutOrNull(timeout)
19
+ }
20
+
21
+ private fun usingWithTimeout (timeout : Long ) {
16
22
viewModelScope.launch {
17
23
try {
18
- withTimeout(timeOut) {
19
- val recentVersions = api.getRecentAndroidVersions()
20
- uiState.value = UiState .Success (recentVersions)
24
+ val recentVersions = withTimeout(timeout) {
25
+ api.getRecentAndroidVersions()
21
26
}
27
+ uiState.value = UiState .Success (recentVersions)
22
28
} catch (timeoutCancellationException: TimeoutCancellationException ) {
23
29
uiState.value = UiState .Error (" Network Request timed out!" )
24
30
} catch (exception: Exception ) {
25
31
uiState.value = UiState .Error (" Network Request failed!" )
26
32
}
27
33
}
28
34
}
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
+
29
54
}
0 commit comments