将一个LiveData观察到另一个LiveData Observr中 [英] Observe one LiveData into other LiveData Observr

查看:231
本文介绍了将一个LiveData观察到另一个LiveData Observr中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个LiveData:

  1. MutableLiveData<Int>-用户可以通过点击"+"和-"按钮来选择数字.

  1. 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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆