MutableLiveData: Cannot invoke setValue on a background thread from Coroutine

kike picture kike · Nov 14, 2018 · Viewed 22.7k times · Source

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?

Answer

Amir Hossein Ghasemi picture Amir Hossein Ghasemi · Feb 8, 2020

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

From documentation:

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