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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With