-
Notifications
You must be signed in to change notification settings - Fork 418
/
ExceptionHandlingViewModel.kt
69 lines (60 loc) 路 2.52 KB
/
ExceptionHandlingViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase13
import androidx.lifecycle.viewModelScope
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
import kotlinx.coroutines.*
import timber.log.Timber
class ExceptionHandlingViewModel(
private val api: MockApi = mockApi()
) : BaseViewModel<UiState>() {
fun handleExceptionWithTryCatch() {
uiState.value = UiState.Loading
viewModelScope.launch {
try {
api.getAndroidVersionFeatures(27)
} catch (exception: Exception) {
uiState.value = UiState.Error("Network Request failed: $exception")
}
}
}
fun handleWithCoroutineExceptionHandler() {
val exceptionHandler = CoroutineExceptionHandler { _, exception ->
uiState.value = UiState.Error("Network Request failed!! $exception")
}
uiState.value = UiState.Loading
viewModelScope.launch(exceptionHandler) {
api.getAndroidVersionFeatures(27)
}
}
fun showResultsEvenIfChildCoroutineFails() {
uiState.value = UiState.Loading
viewModelScope.launch {
supervisorScope {
val oreoFeaturesDeferred = async { api.getAndroidVersionFeatures(27) }
val pieFeaturesDeferred = async { api.getAndroidVersionFeatures(28) }
val android10FeaturesDeferred = async { api.getAndroidVersionFeatures(29) }
val versionFeatures = listOf(
oreoFeaturesDeferred,
pieFeaturesDeferred,
android10FeaturesDeferred
).mapNotNull {
try {
it.await()
} catch (exception: Exception) {
// We have to re-throw cancellation exceptions so that
// our Coroutine gets cancelled immediately.
// Otherwise, the CancellationException is ignored
// and the Coroutine keeps running until it reaches the next
// suspension point.
if (exception is CancellationException) {
throw exception
}
Timber.e("Error loading feature data!")
null
}
}
uiState.value = UiState.Success(versionFeatures)
}
}
}
}