【发布时间】:2019-04-01 11:43:34
【问题描述】:
我有一个 ArrayDeque 类型的 MutableLiveData。 我正在努力观察它。 它在我第一次为其赋值(创建 ArrayDeque)时起作用,但我想做的是观察内容的变化,即添加新条目或删除条目时。
var moveHistory = MutableLiveData<ArrayDeque<Move>>()
..
moveHistory.value = ArrayDeque<Move>() <<--- this fires
moveHistory.value?.addFirst(MontanaMoveStandard(from, to)) <<- this doesn't fire
这是我的观察代码:
moveHistory.observe(this, Observer {
moveHistory -> undoButton?.isEnabled = moveHistory.size > 0
})
【问题讨论】:
-
LiveData 不会在您手动更改对象的内容时触发观察者是引用。你可能想要这样的东西: val data = moveHistory.value; data?.addFirst(MontanaMoveStandard(from, to)); moveHistory.value = 数据;
-
@Luksprog 是的。问题是程序中有很多我更新动作的地方
-
您可以将上面的代码抽象为 MutableLiveData 类的扩展属性/函数。
-
@Luksprog 没想到。我最终所做的是创建一个扩展 MutableLiveData 的类,然后覆盖“值”上的方法。使它们成为扩展功能可能会更整洁。也许有一天我会这样做。 :)
标签: android observable android-livedata