如果您MutableList
为包装值分配一个新值,MutableLiveData
那么它将通知其观察者,但如果您添加/删除其包装值的任何项目,它将不会通知其观察者,因为包装值具有相同的MutableList
对象引用。因此,您的第二个案例是通知您的第一个案例未通知的地方。您可以通过以下扩展来克服此问题MutableLiveData
:
fun <T> MutableLiveData<MutableList<T>>.addNewItem(item: T) {
val oldValue = this.value ?: mutableListOf()
oldValue.add(item)
this.value = oldValue
}
fun <T> MutableLiveData<MutableList<T>>.addNewItemAt(index: Int, item: T) {
val oldValue = this.value ?: mutableListOf()
oldValue.add(index, item)
this.value = oldValue
}
fun <T> MutableLiveData<MutableList<T>>.removeItemAt(index: Int) {
if (!this.value.isNullOrEmpty()) {
val oldValue = this.value
oldValue?.removeAt(index)
this.value = oldValue
} else {
this.value = mutableListOf()
}
}
然后添加/删除您MutableLiveData
喜欢的项目:
// Here is your car list
var carList = MutableLiveData<MutableList<Car>>()
// Add new item to your car list
carList.addNewItem(Car(car.id, color))
// Delete an item from car list at position i
carList.removeItemAt(i)
// Add new item to your car list at position i
carList.addNewItemAt(i, Car(car.id, color))