I have this function in my viewModel which calls a retrofit request in another function, but the Log.i() statement in the function that calls a retrofit request doesn't show in my logcat. I have been told that it is because it runs in another thread. So i tried to return to the main thread, but it still doesn't show.
Here is my viewModel and my function which calls a retrofit request in my original code:
//viewmodel where the Log.i appears
fun getUserList(user: User) {
viewModelScope.launch {
try {
userListResponse = getUsersListRequest(user)
Log.i(
"Tag",
"inside the getUserList function of viewmodel" + userListResponse.toString()
)
} catch (e: Exception) {
errorMessage = e.message.toString()
}
}
}
//result in my logcat : inside the getUserList function of viewmodel[]
//problematic logcat in the function which calls a retrofit request
suspend fun getUsersListRequest(user: User): List<User> =
withContext(Dispatchers.IO) {
return@withContext try {//var user:User = user
val response = RetrofitInstance.api.getUsers("returnUsers", user)
Log.i("Tag", "getUserListRequest response body()" + response.body().toString())
response.takeIf { it.isSuccessful }
?.body() ?: listOf()//this line is the merge of all of the class
} catch (e: Exception) {
listOf()
}
}
//nothing shows in my logcat
Here is my solution attempt:
fun getUserList(user: User) {
viewModelScope.launch {
try {
val response = RetrofitInstance.api.getUsers("returnUsers", user)
Log.i("Tag", "getUserList in viewModel ${response.body().toString()}")
val newList = response.takeIf { it.isSuccessful }?.body() ?: listOf()
viewModelScope.launch { userListResponse = newList }
withContext(Dispatchers.Main) { // Switch to main thread for logging
Log.i(
"Tag",
"getUserListRequest response body: ${response.body().toString()}"
) // Log only the body
}
} catch (e: Exception) {
errorMessage = e.message.toString()
}
}
}
//But nothing appear in my logcat
How can I show the log cat that shows the response.body() of my retrofit request?
The logging is not affected by threads. If you are sure that you haven't accidentally filtered out the log message the only explanation is that the Log.i
isn't actually executed.
Looking at the code you provided that is quite possible: Whenever the retrofit call throws an exception, it is swallowed by the try/catch block and an empty list is returned. All other code after the retrofit call is skipped. Including Log.i
. You can easily verify that if you also put a log statement into the catch
block. One of the two will definitely be called.