Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

android - (Mutable)LiveData is not getting observed on UI

I went threw plenty of similar posts on SO, but still I was not able to find the reason why I am not able to observe the LiveData on the UI.

I am working on a project for learning purposes. What I am trying to do is to fetch a value from my Roomdatabase and display it on the UI. For the sake of clearness, I am showing only the relevant code snippets.

Dao.kt

@Query("SELECT maxValue FROM DoItAgainEntity WHERE id = :id")
    fun getMaxValue(id: Int): LiveData<Int>

Repository.kt

override fun getMaxValue(activityId: Int) = doItAgainDao.getMaxValue(activityId)

ViewModel.kt

private val mMaxValue = MutableLiveData<Int>()

override fun getMaxValue(id: Int): LiveData<Int> =
   Transformations.switchMap(mMaxValue) {
            repository.getMaxValue(id)
   }

Fragment.kt

viewModel.getMaxValue(activitiesAdapter.activities[position].id)

viewModel.getMaxValue(activitiesAdapter.activities[position].id).observe(viewLifecycleOwner, Observer {
     // THIS CODE IS NEVER CALLED
     Log.d("getMaxValueObserver",it.toString())
}

How can I reach the Int value provided in the LiveData object? I know, this is almost a newbie question, but could you please explain me what I am missunderstanding?

Thanks a lot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You do not get your LiveData updated because you do switchMap on mMaxValue. But that LiveData never changes (as I can see from your sample).

You actually do not need the property private val mMaxValue = MutableLiveData<Int>().

You can simplify your function to:

fun getMaxValue(id: Int): LiveData<Int> = repository.getMaxValue(id)

SwitchMap

Returns a LiveData mapped from the input source LiveData by applying switchMapFunction to each value set on source.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...