MutableLiveData: Cannot invoke setValue on a background thread from Coroutine

后端 未结 6 1439
说谎
说谎 2020-12-25 10:27

I\'m trying to trigger an update on LiveData from a coroutine:

object AddressList: MutableLiveData>()
fun getAddressesLiveData(): L         


        
6条回答
  •  生来不讨喜
    2020-12-25 11:09

    You can do one of the following :

    object AddressList: MutableLiveData>()
    fun getAddressesLiveData(): LiveData> {
        AddressList.value = listOf()
        GlobalScope.launch {
            AddressList.postValue(getAddressList())
        }
    
    return AddressList
    }
    

    or

    fun getAddressesLiveData(): LiveData> {
        AddressList.value = listOf()
        GlobalScope.launch {
            val adresses = getAddressList()
            withContext(Dispatchers.Main) {
                AddressList.value = adresses
            }
        }
        return AddressList
    }
    

提交回复
热议问题