如何从mutableLiveData获取数据
我正在尝试从mutableLivedata
获取数据;但是,代码似乎有问题,你们能为我检查吗? 我可以得到对象,但是我未能将对象添加到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")
}
I'm trying to get data from a MutableLiveData
; 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")
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
观察者中的代码只有在
propertyEmlivedata
按下新值时才能运行,或者当您首先观察
IT时它已经具有值。但是来自 docs :因此,直到您的
活动
或fragment
命中onstart()
回调之前,您实际上不会获得值,这意味着您的观察者代码不会运行直到那时。如果您发布的代码要早(例如increate
),那么您要做的是:因为观察者模式,您的代码对对新数据/事件进行了反应 向其推开 ,无论您需要处理该填充的列表,都应是观察者代码的一部分。它应该对新值做出反应并采取行动 - 更新列表视图,提醒用户,启动API调用,
如果
property
是data class
以及您'仅仅复制了所有数据,您就可以将其添加到您的列表中:The code in the observer will only run when
propertyItemLiveData
pushes a new value, or if it already has a value when you firstobserve
it. But from the docs:So you won't actually get a value until your
Activity
orFragment
hits theonStart()
callback, meaning your observer code won't run until then. If the code you posted is running earlier than that (say inonCreate
), then what you're doing 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
btw if
Property
is adata class
and you're just copying all its data, you can add to your list like this:您好,首先是在Kotlin中,您必须使用MutableList,并且需要像这样的任何其他指令的检查。
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 :