When using Retrofit and Coroutines to fetch data from an API I sometimes get an app crash with no stacktrace in Logcat except this: AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
CodePudding user response:
This is usually caused by Retrofit throwing a common exception like UnknownHostException (if there's no Internet) and coroutines swallowing the exception if you didn't specify a CoroutineExceptionHandler.
So add a coroutine exception handler in your launch code, something like this:
val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable ->
throwable.printStackTrace()
}
fun getFromApi() {
viewModelScope.launch(Dispatchers.IO coroutineExceptionHandler) {
retrofitService.getStuffFromInternet()
}
}
Note this just logs the error to Logcat so you can see the missing stacktrace. You still need to figure out what's causing it.
CodePudding user response:
I have encountered this type of error many times and what worked for me was to uninstall the app from the emulator and then installing it again.
