代码之家  ›  专栏  ›  技术社区  ›  Deusnominus

当我的Log.I()不在主线程中时,我如何在我的logcat中显示它?

  •  0
  • Deusnominus  · 技术社区  · 1 年前

    我的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()的日志猫?

    1 回复  |  直到 1 年前
        1
  •  2
  •   tyg    1 年前

    日志记录不受线程的影响。如果您确信没有意外过滤掉日志消息,那么唯一的解释是 Log.i 实际上并没有被执行。

    看看您提供的代码,这是很可能的:每当改装调用抛出异常时,它就会被try/catch块吞噬,并返回一个空列表。所有其他代码 之后 则跳过改装呼叫。包括…在内 日志我 。如果您还将日志语句放入 catch 块两人中的一人肯定会被点名。