我正在尝试从协程触发对 LiveData 的更新:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
AddressList.value = listOf()
GlobalScope.launch {
AddressList.value = getAddressList()
}
return AddressList
}
但我收到以下错误:
IllegalStateException: Cannot invoke setValue on a background thread
有没有办法让它与协程一起工作?
最佳答案
使用 liveData.postValue(value)
而不是 liveData.value = value
.它被称为异步。
来自 documentation :
postValue - Posts a task to a main thread to set the given value.
关于kotlin - 可变实时数据 : Cannot invoke setValue on a background thread from Coroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304347/