Observe one LiveData into other LiveData Observr

不打扰是莪最后的温柔 提交于 2019-12-24 21:42:14

问题


I have two LiveData:

  1. MutableLiveData<Int> -User could choose number by taping at "+" and "-" buttton.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!