首页 > 解决方案 > 在主线程中访问协程时出现非法状态异常

问题描述

我已经编写了下面给出的代码来从本地数据库中获取数据并将其更新到我的回收站视图。我Dispatchers.IO用于从数据库中获取数据并Dispatchers.main用于在回收站视图中更新我的列表。但我无法访问调度程序主模块。我在我的片段中调用以下函数:

viewLifecycleOwner.lifecycleScope.launch(Main) {

    eventList = withContext(IO) {
        shruthiDatabase.eventDao().getAllEvent() as ArrayList<Event_Entity>
    }

    if (eventList.isNotEmpty()) {
        eventAdapter!!.notifyDataSetChanged()
        eventRecycler.visibility = View.VISIBLE
        eventFound.visibility = View.GONE
    }
}

标签: android

解决方案


您的依赖项中可能存在问题。有时,当版本不匹配时,主调度程序不起作用

COROUTINES_VERSION = "1.3.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$COROUTINES_VERSION"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$COROUTINES_VERSION"

推荐阅读