我很麻烦:D我开始使用mvvm和LiveData,我想以更好的方式来做。
我将尝试通过一个简单的例子向您解释我的疑问:
我有一个容器片段“Exams”,其中包含一个ViewPager2,其中包含一些片段“Question”。还有ExamsViewModel和QuestionViewModel。没有db,我唯一的数据源是MyExamDataSource,如下所示:
class MyExamDataSource {
val questions:ArrayList<Question> = ArrayList()
fun saveQuestionResult(){
...
}
fun getQuestion():Question{
...
}
...
...
}
data class Question(val correct:Boolean, val selectedAnswers:ArrayList<Int>)
class ExamViewModel(myExamsDataSource: MyExamsDataSource): ViewModel() {
val correctAnswer:LiveData<Int> = MutableLiveData<Int>(0)
...
...
}
每个QuestionViewModel都会验证自己的问题,但同时,每次有新的正确答案时,正确的Answer LiveData值都应增加。
MyExamData源通过modelfactory传递到ExamsViewModel和QuestionViewModel。
但是现在我有些疑问:
最佳答案
How can I update the correctAnswer LiveData ?
使用对Exams片段的回调。然后,考试片段将更新ViewModel中的正确答案
If I trasform the questions field in a LiveData>, and the ExamsModelView observe it, the onChanged method is not called if I only edit an element of the list or I'm wrong ?
如果将元素添加到列表,它将不会调用观察者。有解决方法。参见Notify Observer when item is added to List of LiveData
Is better to make a directly comunication between modelview ?
ModelViews保存一个或多个 View 的数据。因此,他们不应该互相交流。它与MVVM体系结构背道而驰。如果您处于这样的位置,请考虑将一个ModelView用于多个 View 。这通常是通过使用 Activity 创建一个ModelView来实现的,该 Activity 也保存该 Activity 中所有片段的数据。
关于android - MVVM:从内部 fragment 更新viewpager2的容器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479927/