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) {
    emit ("hello")

    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.

>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”
        myMutableLiveData.value = “World”

        myMutableLiveData.value = someSuspendFunctionRetriever()

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

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

Leave a ReplyCancel reply