Vita Sokolova
05/15/2024, 9:50 AMfun loadData() {
viewModelScope.launch {
try {
greeting.value = async { getGreetingUseCase() }.await()
}
catch (e: CancellationException){
throw e
}
catch (e: Exception) {
greeting.value = "Error occurred!"
}
}
}
But with CoroutineExceptionHandler
it works without crashes.
fun loadDataWithCoroutineExceptionHandler() {
val exceptionHandler = CoroutineExceptionHandler { _, exception ->
greeting.value = "Error occurred!"
}
viewModelScope.launch(exceptionHandler) {
greeting.value = async { getGreetingUseCase() }.await()
}
}
Dmitry Khalanskiy [JB]
05/15/2024, 10:05 AMasync
reports its error in two places:
• The exception is propagated to the parent coroutine (in this case, to viewModelScope.launch
);
• The exception is also stored in the Deferred
as the result of the computation.
When you catch the exception thrown by await
(the second place where the exception is stored), this doesn't stop the launch
from learning that one of its children failed, and so it fails, too.Vita Sokolova
05/15/2024, 12:20 PM