Search code examples
kotlinandroid-livedatakotlin-coroutines

MutableLiveData: Cannot invoke setValue on a background thread from Coroutine


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
}

but I get the following error:

IllegalStateException: Cannot invoke setValue on a background thread

Is there a way to make it work with coroutines?


Solution

  • Use liveData.postValue(value) instead of liveData.value = value. It called asynchronous.

    From documentation:

    postValue - Posts a task to a main thread to set the given value.