MutableLiveData:无法在协程的后台线程上调用setValue [英] MutableLiveData: Cannot invoke setValue on a background thread from Coroutine
本文介绍了MutableLiveData:无法在协程的后台线程上调用setValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从协程触发LiveData更新:
I'm trying to trigger an update on LiveData from a coroutine:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
AddressList.value = listOf()
GlobalScope.launch {
AddressList.value = getAddressList()
}
return AddressList
}
但出现以下错误:
IllegalStateException:无法在后台线程上调用setValue
IllegalStateException: Cannot invoke setValue on a background thread
有没有办法使其与协同程序一起工作?
Is there a way to make it work with coroutines?
推荐答案
使用liveData.postValue(value)
代替liveData.value = value
.这称为异步.
Use liveData.postValue(value)
instead of liveData.value = value
. It is called asynchronous.
来自文档:
postValue -将任务发布到主线程以设置给定值.
postValue - Posts a task to a main thread to set the given value.
这篇关于MutableLiveData:无法在协程的后台线程上调用setValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文