kotlin - 可变实时数据 : Cannot invoke setValue on a background thread from Coroutine

标签 kotlin android-livedata kotlin-coroutines

我正在尝试从协程触发对 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/

相关文章:

kotlin - 从两个线程更改不可变数据结构

如果计划任务花费的时间超过特定时间,Java 将停止计划任务

android - 何时使用 MutableLiveData 和 LiveData

android - 使用 Kotlin 协程替换 LocalBroadcastManager 以进行 Firebase 消息传递

Android资源链接在绑定(bind)适配器数据绑定(bind)中失败

java - MediaSessionCompat :Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent

java - Spring Data 与 JPA 2.2 resultStream 到 Kotlin 的 Flow

android - Rxjava 与 kotlin 协程

android - 将关键字与 Unsplash API 一起使用的搜索 View

android - 使用协程和 LiveData 实现 EventBus