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:
valerror:MutableLiveData<String>=MutableLiveData()valcoroutineExceptionHandler=CoroutineExceptionHandler{coroutineContext,throwable->// handle thrown exceptions from coroutine scopeerror.postValue(throwable.stackTrace.toString())}fungetObjectFromNetwork(){viewModelScope.launch(coroutineExceptionHandler){valresponse=networkRepository.getObject()}}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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. TheViewModel
might be the ideal place for that logic in which case you wouldn't want to use thissafeLaunch
extension. Just define your own handler and pass it in tolaunch
.In your VM: