观察数据类属性变化的可变实时数据 [英] Observe mutable live data of a data class's property changes
问题描述
在 Android Kotlin 基础知识,代码提到使用后备属性将 MutableLiveData
封装在 ViewModel
中,以便只有 ViewModel
本身可以更改所述可变值.与实践不同,我使用的是数据类.我想观察数据类的属性变化并在UI中显示.
In Android Kotlin Fundamentals, the code mentions of using a backing property to encapsulate the MutableLiveData
in ViewModel
so that only the ViewModel
itself can change said mutable value. Different from the practice, I'm using a data class instead. I would like to observe the changes to the property of the data class and display it in the UI.
这是我目前所拥有的.
class CourseViewModel : ViewModel() {
private var _lastAccessedCourse: MutableLiveData<Course>
val lastAccessedCourse: LiveData<Course>
get() = _lastAccessedCourse
// Some other code...
fun updateProgress() {
if (_lastAccessedCourse.value != null)
_lastAccessedCourse.value = _lastAccessedCourse.value!!.let {
it.progress += 5
it
}
}
然后,我将在我的 UI 中观察 lastAccessedCourse
,如下所示.单击按钮会更新变量 progress
,而我正在观察这种变化.
Then, I will observe the lastAccessedCourse
in my UI like below. A button click updates the variable progress
and that change is what I am observing.
binding.fragHomeLaReadButton.setOnClickListener {
courseViewModel.updateProgress()
}
courseViewModel.lastAccessedCourse.observe(viewLifecycleOwner, Observer {
binding.fragHomeLaProgress.progress = it.progress
})
我的数据类很简单.
data class Course(
var name: String,
var category: String,
var progress: Int
)
这有效.不过,我有一个顾虑.当我尝试 updateProgress()
而不设置 _lastAccessedCourse
变量(而只是将 5
添加到进度)时,似乎更改不是观察到的.我怀疑这是因为它没有观察到数据类的属性变化.这是正确的吗?
This works. However, I have a concern. When I tried to updateProgress()
without setting _lastAccessedCourse
variable (and instead just adding 5
to progress), it seems like the change isn't observed. I suspect that this is because it doesn't observe the data class's property changes. Is this correct?
可以看出,每次调用 updateProgress()
时,我都会向 _lastAccessedCourse
变量返回一个新的 Course
.这有性能缺陷吗?有没有更好的做法来实现我想要的?
As can be seen, I'm returning a new Course
to _lastAccessedCourse
variable every time I call updateProgress()
. Does this have a performance drawback? Is there a better practice to achieve what I want?
推荐答案
MutableLiveData
仅在 value
更改时通知其观察者.未观察到对课程的更改(在您的情况下为 Course
).
A MutableLiveData
only notifies its observers if the value
is changed. Changes to the class (Course
in your case) are not observed.
为了最佳实践,请考虑为 Course
使用一个不可变的数据类,并每次为 LiveData
分配一个新的数据类:
For best practice, consider using an immutable data class for Course
and assigning a new one to the LiveData
each time:
data class Course(
val name: String,
val category: String,
val progress: Int
)
val course = /* TODO: get current course */
val newCourse = course.copy(progress = course.progress + 5)
_lastAccessedCourse.value = newCourse
这篇关于观察数据类属性变化的可变实时数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!