Answers
You need to wrap the entire Retrofit call inside the try-catch
. Retrofit throws IOException when the device is offline or the server is unreachable.
LaunchedEffect(Unit) {
try {
val todosresponse = RetrofitInstance.api.gettodo()
if (todosresponse.isSuccessful && todosresponse.body() != null) {
todos = todosresponse.body() ?: emptyList()
Log.e("Api_CALL", "Got data")
} else {
todos = emptyList()
error = "Server Error: ${todosresponse.code()}"
}
} catch (e: IOException) {
// Network error like no internet
error = "No internet connection."
todos = emptyList()
Log.e("NetworkError", "IOException: ${e.localizedMessage}")
} catch (e: Exception) {
// Other unexpected errors
error = "Unexpected error occurred."
todos = emptyList()
Log.e("UnknownError", "Exception: ${e.localizedMessage}")
} finally {
loading = false
}
}
and
Don’t compare lists like if (todos == emptyList<todos>())
Instead, use .isEmpty():
else if (todos.isEmpty())
{
Text("No Data", modifier = Modifier.align(Alignment.Center))
}