Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specify an existing LiveData object for the liveData kotlin builder function

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading