- This use case uses the suspending function
withTimeout()
from the coroutines-core library.
- It throws a TimeoutCancellationException if the timeout was exceeded.
- You can set the duration of the request in the UI and check the behavior when the response time is bigger than the timeout.
class NetworkRequestWithTimeoutViewModel(
private val api: MockApi = mockApi()
) : BaseViewModel<UiState>() {
fun performNetworkRequest(timeout: Long) {
uiState.value = UiState.Loading
// usingWithTimeout(timeout)
usingWithTimeoutOrNull(timeout)
}
private fun usingWithTimeout(timeout: Long) {
viewModelScope.launch {
try {
val recentVersions = withTimeout(timeout) {
api.getRecentAndroidVersions()
}
uiState.value = UiState.Success(recentVersions)
} catch (timeoutCancellationException: TimeoutCancellationException) {
uiState.value = UiState.Error("Network Request timed out!")
} catch (exception: Exception) {
uiState.value = UiState.Error("Network Request failed!")
}
}
}
private fun usingWithTimeoutOrNull(timeout: Long) {
viewModelScope.launch {
try {
val recentVersions = withTimeoutOrNull(timeout) {
api.getRecentAndroidVersions()
}
if (recentVersions != null) {
uiState.value = UiState.Success(recentVersions)
} else {
uiState.value = UiState.Error("Network Request timed out!")
}
} catch (exception: Exception) {
uiState.value = UiState.Error("Network Request failed!")
}
}
}
}