kotlin: IllegalStateException: Cannot invoke setValue on a background thread

suspend函數中報瞭如下的異常日誌: 
 java.lang.IllegalStateException: Cannot invoke setValue on a background thread
        at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:461)
        at androidx.lifecycle.LiveData.setValue(LiveData.java:304)
        at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
        at app.ra9.viewmodels.MemberListViewModel.getGroupMember(MemberListViewModel.kt:41)
        at app.ra9.viewmodels.MemberListViewModel$getGroupMember$1.invokeSuspend(Unknown Source:11)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)

錯誤代碼的樣子:

   suspend fun getGroupMember() {
        val result = createMemberUseCase(groupId)
            _allMembers.value = result.value
    }

 

解決方案:將報錯部分的代碼加上:

withContext(Dispatchers.IO){

}
  suspend fun getGroupMember() {
        val result = createMemberUseCase(groupId)
        withContext(Dispatchers.Main) {
            _allMembers.value = result.value
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章