Home > OS >  Specify an existing LiveData object for the liveData kotlin builder function
Specify an existing LiveData object for the liveData kotlin builder function

Time:12-05

For example, we can create a LiveData object using a liveData builder function:

var liveData: LiveData<String> = liveData(Dispatchers.IO) {
    delay(1000)
    emit ("hello")

    delay(1000)
    emit ("world")
}

This is useful in ViewModel, I create a LiveData object that receives multiple data values from an asynchronous heavy function in one line.

But what if I already have a MutableLiveData object and just want to post values there, without creating a new LiveData object? How can I do this?

I need a way to asynchronously emit multiple values into existed MutableLiveData object inside a ViewModel scope to automatically finish all running tasks when the ViewModel will be cleared.

CodePudding user response:

You can post to a MutableLiveData in a coroutine launched from viewModelScope.

private val myMutableLiveData = MutableLiveData<String>()

fun someFun() {
    viewModelScope.launch {
        myMutableLiveData.value = “Hello”
        delay(500L)
        myMutableLiveData.value = “World”

        myMutableLiveData.value = someSuspendFunctionRetriever()

        val result = withContext(Dispatchers.IO) {
            someBlockingCallRetriever()
        }
        myMutableLiveData.value = result

        // or use post() when not on Main dispatcher:
        withContext(Dispatchers.IO) {
            val result = someBlockingCallRetriever()
            myMutableLiveData.post(result)
        }
    }
}
  • Related