I'm trying to get data from a mutableDataLive; however, it seems like something is wrong with the code, can you guys check for me please? I can get the object, but I failed to add the object to a mutableList
properties = ArrayList()
propertyViewModel.propertyItemLiveData.observe(
viewLifecycleOwner,
Observer { propertyItems ->
for (property in propertyItems){
var p:Property = Property(property.id,property.address
,property.price,property.phone,property.lat,property.lon)
println(p)// i can display data
properties.add(p)//when i add to properties, the properties still null. Why?
}
}
)
if (properties.isEmpty()){
println("null")
}
CodePudding user response:
The code in the observer will only run when propertyItemLiveData
pushes a new value, or if it already has a value when you first observe
it. But from the docs:
As soon as an app component is in the
STARTED
state, it receives the most recent value from theLiveData
objects it’s observing. This only occurs if theLiveData
object to be observed has been set.
So you won't actually get a value until your Activity
or Fragment
hits the onStart()
callback, meaning your observer code won't run until then. If the code you posted is running earlier than that (say in onCreate
), then what you're doing is:
- creating an empty list
- adding an observer that will add stuff to that list (but it won't run until later)
- checking if the list is still empty (it definitely is)
Because of the observer pattern, where your code reacts to new data/events being pushed to it, whatever you need to do with that populated list should be part of the observer code. It should react to the new value and take action - update a list view, alert the user, start an API call, whatever
propertyViewModel.propertyItemLiveData.observe(viewLifecycleOwner) { propertyItems ->
// handle the propertyItems, add them to your list etc
// then do whatever needs to happen with the list, e.g. display it
updateDisplay(propertyList)
}
btw if Property
is a data class
and you're just copying all its data, you can add to your list like this:
properties.addAll(propertyItems.map { it.copy() })
// or propertyItems.map(Property::copy)
CodePudding user response:
hello first of all in kotlin in general you have to use mutableList and the check of empty or any other instruction should inside the call back like this :
properties = mutableListOf<YourClass>()
propertyViewModel.propertyItemLiveData.observe(
viewLifecycleOwner,
Observer { propertyItems ->
for (property in propertyItems){
var p:Property = Property(property.id,property.address
,property.price,property.phone,property.lat,property.lon)
println(p)// i can display data
properties.add(p)//when i add to properties, the properties
}
if (properties.isEmpty()){
println("null")
}
}
)