java.lang.IllegalStateException:无法在后台线程上调用 observe

java.lang.IllegalStateException: Cannot invoke observe on a background thread

提问人:Murphler 提问时间:4/3/2021 更新时间:4/3/2021 访问量:217

问:

我正在尝试实施一个在线教程。当我打开一个特定的片段时,应用程序崩溃了,标题中的错误消息是 logcat 转发给我的。导致问题的代码片段粘贴如下:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProvider(this, viewModelFactory).get(ConditionsViewModel::class.java)
    bindUI()
}

private fun bindUI() = GlobalScope.launch{
    val getConditions = viewModel.conditions.await()
    getConditions.observe(viewLifecycleOwner, Observer {
        if(it == null) return@Observer

        tvConditions.text = it.toString()
    })
}

因此,bindUI() 方法是在 onCreate() 中调用的,导致异常的行是在调用 Observer 时调用的。如果有人能指导我了解导致这种情况的原因,我们将不胜感激。

非常感谢

安卓 Kotlin

评论


答:

0赞 Henry Twist 4/3/2021 #1

视图模型不应异步返回。相反,您应该异步查询终结点,然后在获得结果后填充终结点。conditionsLiveDataLiveData

除非必要,否则您可能也不应该使用。相反,您可以使用视图模型本身的作用域。GlobalScope

所以像这样:

查看模型

val conditions = MutableLiveData<>()

init {

    viewModelScope.launch {

        conditions.value = ...
    }
}

活动

conditions.observe(viewLifecycleOwner) {

    ...
}

评论

0赞 Murphler 4/3/2021
非常感谢。我有点理解。但是,在充实您的实现时遇到了一些麻烦 - 对不起,我是一个完全的初学者。因此,在ViewModel中,我尝试实现以下内容: val conditions = MutableLiveData<CurrentConditionsSpecified>() init { viewModelScope.launch { conditions.value = conditionsRepository.getCurrentConditions() } } 我在 conditionsRepository.getCurrentConditions() 上收到类型不匹配,它说 Required: CurrentConditionsSpecified?找到: LiveData<CurrentConditionsSpecified>
0赞 Henry Twist 4/3/2021
你在为什么而苦苦挣扎?
0赞 Murphler 4/3/2021
我在设置值 = conditionsRepository.getCurrentConditions() 时遇到类型不匹配,我假设因为它是 MutableLiveData,应该将 null 检查放在某个地方,但似乎无法弄清楚在哪里
0赞 Henry Twist 4/3/2021
是挂起功能吗?getCurrentConditions()
0赞 Murphler 4/3/2021
这是一个挂起功能,是的