0

What is the difference between livedata and mutableLiveData? When can both observe the new value?

1 Answers1

7

The only key difference between LiveData and MutableLiveData is that you can change the value of MutableLiveData but LiveData does not allow you to change it's value. LiveData only allow you to observe and utilize it's value.

They both are normally used together, MutableLiveData is used to record the changed value and LiveData is used to notify the UI about the change value. For Example

class SampleViewModel(): ViewModel() {
    private val _sampleString = MutableLiveData<String>()
    val sampleString: LiveData<String> get() = _sampleString

    fun setSampleString(temp: String) {
        _sampleString.value  = temp
    }
}

class MainActivity: AppCompatActivtiy {
   private val viewModel: SampleViewModel by viewModels()

   //in onCreate
    viewModel.sampleString.observe(this) {
        //here you will have the value sampleString, that you can use as you want.
    }   
    
    //that is how you can update the value of MutableLiveData 
    viewModel.setSampleString("random string")

}

Here, as soon as you will assign the the value to MutableLiveData _sampleString, LiveData sampleString will be notified and will notify the changes made in it. LiveData observes the new value as soon as new value is updated in MutableLiveData.

I hope this has cleared your doubts.

Kashif Masood
  • 286
  • 1
  • 6