DEV Community

Discussion on: Safely Launch Exception-Ready Coroutines

Collapse
 
robotsquidward profile image
A.J. Kueterman • 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
  error.postValue(throwable.stackTrace.toString())
}

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