我正在尝试使用 Delegates.observable()
以便在 MutableList
发生更改时收到通知。
val items: MutableList<Item> by Delegates.observable(startingItems) {
_, old, new ->
Log.e("observable", "${old.size} -> ${new.size}")
}
但是每当我尝试从列表中删除或添加内容时,什么都没有发生。我的意思是 Logcat 中没有日志的踪迹,因为它应该在那里。
最佳答案
docs状态:
Observable
Delegates.observable()
takes two arguments: the initial value and a handler for modifications. The handler gets called every time we assign to the property (after the assignment has been performed). It has three parameters: a property being assigned to, the old value and the new one.
在您的情况下,您没有分配给 items
,您只添加到现有实例。永远不会调用回调。
建议:对只读的 List
使用可变属性,并在添加新元素时重新分配它:
var items: List<String> by Delegates.observable(mutableListOf()) { _, old, new ->
println("changed")
}
//add like this:
user.items += "new val"
plus
运算符不会调用列表上的 add
,而是创建一个包含所有旧元素和新元素的新实例。
关于android - 使用 MutableList 时,Delegates.observable() 未收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49056590/