问题
I have two LiveData
:
MutableLiveData<Int>
-User could choose number by taping at "+" and "-" buttton.LiveData> - it's my data from RoomData base by call method
getLessonsForThatDay(number:Int)
.
I have to update my method getLessonForThatDay(value) with that MutableLiveData value.
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
})
})
- List item
回答1:
First in your viewmodel
define a liveData
like this.
private val dayOfWeekChangRequest = MutableLiveData<Int>()
and a method like this, when + , - clicked, call this method.
fun dayOfWeekChanged(dayOfWeek: Int) {
dayOfWeekChangRequest.value = dayOfWeek
}
now add a live data for lessonsOfThatDay
val lessonsForThatDay: LiveData<List<Lesson>> = Transformations
.switchMap(dayOfWeekChangRequest) { day ->
yourDataBaseRepository.getLessonsOfThatDay(day)
}
with this transformation, every time you change your dayOfWeek
, the lessonsForThatDay
value will be changed.
at last in your activity observe it
viewModel.lessonsForThatDay.observe(viewLifecycleOwner, Observer {
lessons ->
adapter.updateData(lessons)
subjectsListTimetableRecyclerView.layoutManager = LinearLayoutManager(context)
subjectsListTimetableRecyclerView.adapter = adapter
})
回答2:
You can do viewModel = Dao.getLessonsForThatDay(number)
. This way, the viewmodel will listen to changes in Dao
来源:https://stackoverflow.com/questions/57220927/observe-one-livedata-into-other-livedata-observr