What’s the best way to retrieve LiveData value in ...
# android-architecture
v
What’s the best way to retrieve LiveData value in a click listener? Is it ok to just perform a null check to synchronously get the livedata value?
Copy code
button.setOnClickListener {
     if (viewmodel.getMyLiveData().value != null) {
         // do something
     }
}
a
use
viewmodel.getMyLiveData().value != null
g
it's fine as long as the livedata is observed somewhere else. ex. MediatorLiveData won't update it's value if it's not actively observed.
r
I would argue if the view needs to get the livedata instead of observe it, than it probably doesnt need to be a live data object
A better way is to just notify the viewmodel that a clicking action happen and just observe the response. That way the flow of communication flows in one direction, with each layer just observing the reaction of the next layer
👍 1
v
@Aslam Hossin That was a typo on my part. Forgot the
.value
call. Added it in
👍 1
@rkeazor If I notify the VM of a click, I would still need to synchronously get the livedata value inside the VM and perform a null check right?
r
You would add a observer to the livedata or live event rather
i
It’s actually a design flaw.
You need to notify the viewModel of the click.
Than it will update a live-data that you are observing
doing viewModel.getLiveData() is never necessary
unless it’s to observe it
v
@Ianmedeiros So say I notify viewmodel on the click
viewmodel.doSomething()
, if there is a livedata in my viewmodel whose value I want to retrieve before firing off a live event. Wouldn’t I still need to do viewmodel.getMyLiveData().value? Like so?
Copy code
fun doSomething() {
   getMyLiveData().value?.let { myString ->
        // fireOff live event with myString
   }   
}
i
the fireOff will change another live data.
v
yes, a live event liveData
i
you will not need to do this on view
because doSomething() lives inside the ViewModel that already have the live data (or other member) with the value you need
So. You view is only observing the live data that will change in the “fireOff”
v
yes, but my question was more related to getting the getMyLiveData value synchronously vs observing it
i
Probably getMyLiveData() doesn’t actually needs to be a live data
v
It does, since it can be updated from multiple source and multiple observers are listening for changes to that value
i
the .value will get the value synchronously. It’s fine