https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
v

voben

08/07/2019, 6:48 PM
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

Aslam Hossin

08/08/2019, 2:12 AM
use
viewmodel.getMyLiveData().value != null
g

gergo

08/08/2019, 11:44 AM
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

rkeazor

08/08/2019, 1:42 PM
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

voben

08/08/2019, 2:28 PM
@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

rkeazor

08/08/2019, 3:17 PM
You would add a observer to the livedata or live event rather
i

Ianmedeiros

08/08/2019, 6:24 PM
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

voben

08/08/2019, 7:03 PM
@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

Ianmedeiros

08/08/2019, 7:05 PM
the fireOff will change another live data.
v

voben

08/08/2019, 7:05 PM
yes, a live event liveData
i

Ianmedeiros

08/08/2019, 7:05 PM
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

voben

08/08/2019, 7:07 PM
yes, but my question was more related to getting the getMyLiveData value synchronously vs observing it
i

Ianmedeiros

08/08/2019, 7:07 PM
Probably getMyLiveData() doesn’t actually needs to be a live data
v

voben

08/08/2019, 7:08 PM
It does, since it can be updated from multiple source and multiple observers are listening for changes to that value
i

Ianmedeiros

08/08/2019, 7:14 PM
the .value will get the value synchronously. It’s fine
4 Views