Getting null value after setting the value of a variable inside observe block

Issue

In my UI – MainActivity.kt

I have:

private var recommendationCount: Int? = null

onCreate{
   
   viewmodel.recommended.observe(this){
      recommendationCount = it.size
   }
   
   //I need to set the view outside the observe
   binding.myTextView.text = recommendationCount.toString()
   
   //it returns null
  
}

When I set my textview outside the observe block, it returns a null value. but when I set it inside, it returns the correct value.

I need to set it outside.

Solution

Since you want to merge the values from multiple LiveData, you need to combine them into a single LiveData. You can’t just grab data from each of them sequentially, because LiveData is not intended to work synchronously (you can use the value property, but this is not robust because it’s possible to check the value before its initial value is set).

You need to combine them into a single LiveData or Flow by merging them. It can be done with LiveData using MediatorLiveData, but it’s easier with Flows because you can use the combine function. You could do something like this, converting flows and back to LiveData to avoid having to use coroutines:

val combinedLiveData = combine(
        liveDataA.asFlow(), 
        liveDataB.asFlow(), 
        liveDataC.asFlow()
    ) { a, b, c -> 
        a + b + c 
    }.asLiveData()

But if you are using coroutines, you wouldn’t need to convert back to LiveData.

Answered By – Tenfour04

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published