MutableLiveData: Cannot invoke setValue on a background thread from Coroutine

后端 未结 6 1462
说谎
说谎 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:13

    If you want to updated UI by using Coroutines, there are 2 ways to achieve this

    GlobalScope.launch(Dispatchers.Main):

    GlobalScope.launch(Dispatchers.Main) {
        delay(1000)     // 1 sec delay
        // call to UI thread
    }
    

    And if you want some work to be done in background but after that you want to update UI, this can be achieved by the following:

    withContext(Dispatchers.Main)

    GlobalScope.launch {
        delay(1000)     // 1 sec delay
    
        // do some background task
    
        withContext(Dispatchers.Main) {
                // call to UI thread
        }
    }
    

提交回复
热议问题