0

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
Cizzl
  • 324
  • 2
  • 11
rogalz
  • 80
  • 8

2 Answers2

0

You can do viewModel = Dao.getLessonsForThatDay(number). This way, the viewmodel will listen to changes in Dao

potatoxchip
  • 516
  • 1
  • 7
  • 20
0

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
    })
Mojtaba Haddadi
  • 1,346
  • 16
  • 26