我的viewModel中有这个函数,它在另一个函数中调用改装请求,但调用改装请求的函数中的Log.I()语句没有显示在我的logcat中。有人告诉我,这是因为它在另一个线程中运行。所以我试着回到主线程,但它仍然没有显示出来。
这是我的viewModel和函数,它在我的原始代码中调用改装请求:
//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
以下是我的解决方案尝试:
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
如何显示显示改装请求的response.body()的日志猫?