8

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.

2
  • this is because you are observing your list, not your list items. Dec 15, 2018 at 8:52
  • if you want to update your favorite status on your view than you can have favorite variable as MutableLiveData and bind it with your view. view will get updated for every new value for favorite variable. Dec 15, 2018 at 9:02

1 Answer 1

10

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.