android - 使用 MutableList 时,Delegates.observable() 未收到通知

标签 android kotlin

我正在尝试使用 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/

相关文章:

java - Firebase:从 Firebase 自动设置提醒

java - 尝试通过嵌入式 Jetty 服务器运行 Ktor 应用程序时如何避免 java.lang.ExceptionInInitializerError?

windows - 如何运行Kotlin/Native win32示例

kotlin - 在 Kotlin 中使用索引迭代 IntArray 的最佳方法

应用程序的 Android 调试/发布版本

android -- 关于singleTask模式的问题

android - 更新列表元素内容时 Jetpack Compose : No recomposition happening,

kotlin - 什么时候应该使用加号、减号、时间函数而不是 Kotlin 中的运算符?

java - 在 fragment 中使用外部字体

java - Exoplayer 不显示字幕