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.
CodePudding user response:
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)
CodePudding user response:
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.