Reputation: 2781
I am using Live Data in my application and I have a view model that extends from ViewModel
.
In my view model, I have a list that is:
var songs: MutableLiveData<List<Song>> = MutableLiveData<List<Song>>()
In a function in my view model I do this:
songs.value?.find { it.id == song.id }.also {
when (song.isFavorite) {
true -> song.isFavorite = false
false -> song.isFavorite = true
}
}
I will change a boolean in an item in songs
and in m fragment I observe this list like below:
viewModel.songs.observe(this , Observer {
Log.d(TAG , "songs changed")
})
But songs will not notify after this change.
Why does this happen?
Thankyou for your answers.
Upvotes: 8
Views: 21864
Reputation: 490
How live data works is, when the value of the livedata changes then it will be notified for eg:
Let your data class of song:
data class Song(name : String?)
In ViewModel:
val songLiveData = MutableLiveData<Song?>
In your activity:
viewModel.songLiveData.observe(this , Observer {
Log.d(TAG , "songs changed")
})
songLiveData.value = Song(name = "Name of Song")
This will work.
When you call setValue of the live data than the callback comes to the observer.
private val songsLiveData = MutableLiveData<List<Song?>>()
init {
songsLiveData.value = ArrayList()
}
fun editSong() {
//change all the things in you live data
songsLiveData.value = songsLiveData.value//this will give the callback to you observer
}
Upvotes: 11