DEV Community

Discussion on: Safely Launch Exception-Ready Coroutines

jessefeng profile image
Jingzhe(Jesse) Feng

Is there anyway we can change mutable livedata instead of throwable.printStackTrace()

robotsquidward profile image
A.J. Kueterman Author • Edited

If you want to make an extension function on CoroutineScope then you abstract that error handling away from your VM - easier for establishing default exception handling but might not be where you want to encapsulate your logic. The ViewModel might be the ideal place for that logic in which case you wouldn't want to use this safeLaunch extension. Just define your own handler and pass it in to launch.

In your VM:

val error: MutableLiveData<String> = MutableLiveData()

val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
  // handle thrown exceptions from coroutine scope

fun getObjectFromNetwork() {
  viewModelScope.launch(coroutineExceptionHandler) {
    val response = networkRepository.getObject()