I am using Retrofit with coroutines (built in support). I have a Retrofit interface, retrofit implementation and the API implementation created by Retrofit, but it doesn't matter as it doesn't get called. It crashes before that, here:
In XService.kt
suspend fun test() {
val mediaType = MediaType.parse("text/plain")
val requestBody = RequestBody.create(mediaType, "TEST STRING") // Crashes here
// Now make some network requests
}
which is called by a viewModel:
suspend fun test() {
return withContext(viewModelScope.coroutineContext) {
service.test()
}
}
which is called by a Fragment:
lifecycleScope.launch() { model.test() }
Unhelpful error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: package_name, PID: 9729
I/Process: Sending signal. PID: 9729 SIG: 9
I'm just not sure why creating a RequestBody
causes a crash. What is weird is, when debugging and going slowly through the code, it doesn't crash... I have simplified the code so its easier for you to read, but the reason why its scoped to Fragment, not VM is because I want the Fragment to change the UI based on the response.
EDIT: It turns out if I wrap it in a try/ catch block, the line which crashes usually doesn't crash. Instead, the network call afterwards does, giving printing out:
I/System.out: java.net.UnknownHostException: Unable to resolve host "qats.orth.uk": No address associated with hostname
try {
val requestBody = RequestBody.create(mediaType, mode.toString())
return api.createQuiz(requestBody).createResult()
} catch (e: Exception) {
println(e)
}
So I am confused. Why does putting it in a try/catch block change what error message I get. Without try/catch, I got a useless crash with no stacktrace. I guess this may be the challenge with coroutines.