问题描述
我有两个LiveData
:
-
MutableLiveData<Int>
-用户可以通过点击"+"和-"按钮来选择数字.
MutableLiveData<Int>
-User could choose number by taping at "+" and "-" buttton.
LiveData>-这是我通过调用方法getLessonsForThatDay(number:Int)
从RoomData库获得的数据.
LiveData> - it's my data from RoomData base by call method getLessonsForThatDay(number:Int)
.
我必须使用该MutableLiveData值更新我的方法getLessonForThatDay(value).
I have to update my method getLessonForThatDay(value) with that MutableLiveData value.
我尝试使用MediatorLiveData<>,但我不明白.
I've tried to use MediatorLiveData<> but i don't get it.
viewModel.dayOfWeek.observe(viewLifecycleOwner, androidx.lifecycle.Observer { dayOfWeekValue ->
d("$dayOfWeekValue")
viewModel.getLessonsForThatDay(dayOfWeekValue).observe(viewLifecycleOwner, androidx.lifecycle.Observer { lessons ->
adapter.updateData(lessons)
subjectsListTimetableRecyclerView.layoutManager = LinearLayoutManager(context)
subjectsListTimetableRecyclerView.adapter = adapter
})
})
- 列表项
推荐答案
首先在viewmodel
中定义这样的liveData
.
private val dayOfWeekChangRequest = MutableLiveData<Int>()
和类似的方法,单击+时,单击该方法.
and a method like this, when + , - clicked, call this method.
fun dayOfWeekChanged(dayOfWeek: Int) {
dayOfWeekChangRequest.value = dayOfWeek
}
现在为lessonsOfThatDay
val lessonsForThatDay: LiveData<List<Lesson>> = Transformations
.switchMap(dayOfWeekChangRequest) { day ->
yourDataBaseRepository.getLessonsOfThatDay(day)
}
通过此转换,每次更改dayOfWeek
时,lessonsForThatDay
值都会更改.
with this transformation, every time you change your dayOfWeek
, the lessonsForThatDay
value will be changed.
最后在活动中观察
viewModel.lessonsForThatDay.observe(viewLifecycleOwner, Observer {
lessons ->
adapter.updateData(lessons)
subjectsListTimetableRecyclerView.layoutManager = LinearLayoutManager(context)
subjectsListTimetableRecyclerView.adapter = adapter
})
这篇关于将一个LiveData观察到另一个LiveData Observr中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!