简体   繁体   中英

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

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.

You cannot set it outside the observer simply because the onCreate() executes all the code inside it before the viewModel changes the value of the Observable(Live data, I guess) that you are observing in onCreate() As a solution, you can give your variable a default value which will be changed in the observer block when the viewModel changes the value of the Observable(Live data, I guess)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM