我的viewModel中有这个函数,它在另一个函数中调用 retrofit 请求,但调用 retrofit 请求的函数中的Log.i()陈述没有显示在我的logcat中.有人告诉我,这是因为它在另一个线程中运行.所以我try 返回主线程,但仍然没有显示.
这是我的viewModel和我的函数,它在我的原始代码中调用 retrofit 请求:
//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
以下是我的解决方案try :
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
如何显示我的改装请求的respect.body()的日志(log)cat?