Home>

I have a fragment and its viewmodel with a repository. Every time my target ID changes, I callviewModel.initFocusGoal ()to get a new LiveData from Room for a new target.

But it returns null to me every time. Even observe doesn't work.

What could this be related to? Maybe there are other solutions for this problem?

HomeFragment:

viewModel.initFocusGoal ()
viewModel.getFocusGoal (). observe (requireActivity (), {
    println (it)
})

HomeViewModel:

var currentGoal: LiveData <
Goal >
= repository.currentGoal
fun getFocusGoal (): LiveData <
Goal >
 {
     return currentGoal
}
fun initFocusGoal () {
    repository.initGoal (CURRENT_GOAL_ID)
}

HomeRepository:

var currentGoal: LiveData <
Goal >
= MutableLiveData ()
fun initGoal (id: Long) {
    currentGoal= goalDao.getLiveById (id)
}

GoalDao:

@Query ("SELECT * FROM goal WHERE id=: id")
fun getLiveById (id: Long): LiveData <
Goal >
  • Answer # 1

    Don't do that.
    LiveData has its own "address". And observe listeners subscribe to this "address". You have a new LiveData returned from the database with a new "address" and the listeners do not know about it.
    Try changing your code to the following

    val currentGoal: LiveData <
    Goal >
    = MutableLiveData () //LiveData is better done VAL
    //when the response comes from the database, you only need to change the value in LD, and not all of it (the problem with the new "address")
    fun initGoal (id: Long) {
        currentGoal.value= goalDao.getLiveById (id)
    }
    @Query ("SELECT * FROM goal WHERE id=: id")
    fun getLiveById (id: Long): Goal