https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lukas Lechner

08/19/2020, 12:33 PM
Is it possible to install a
CoroutineExceptionHandler
in a
viewModelScope
when e.g. initialising an Android
ViewModel
? I want that exceptions by every Coroutine that are then started in this scope are then handled by the handler.
g

Gabriel Feo

08/19/2020, 1:31 PM
Can’t set it on an existing scope, you’d create a new scope out of viewModelScope + CoroutineExceptionHandler { }
Can’t find the reference on viewModelScope anywhere, is that overridable?
c

Christopher Elías

08/20/2020, 2:40 PM
Ive got something like this:
Copy code
abstract class BaseViewModel : ViewModel() {

    private val mapperExceptionHandler = CoroutineExceptionHandler { _, throwable ->
        setErrorFromMapperPresentation(throwable.message)
    }

    val presentationMapperContext : CoroutineContext = <http://Dispatchers.IO|Dispatchers.IO> + mapperExceptionHandler
And use it like this:
private val _ranking = MutableLiveData<SellRanking>()
val ranking : LiveData<RankingModel> = _ranking.switchMap {
liveData(presentationMapperContext) {
emit(mapper.rankingDomainToPresentation(it))
}
}
2 Views