4

In many samples i see that:

 class DataViewModel{
         val data:LivaData<Int>
             get() = _data 

         private val _data = MutableLiveData<Int>()

    }

But more simply looks like this:

 class DataViewModel{
         val data = MutableLiveData<Int>()

    }

so, why need this more complicated code construction with 2 fields?

Serg Burlaka
  • 2,351
  • 24
  • 35
  • So dependents of your viewmodel cannot update the value of your mutable live data object. – RedShirt Feb 08 '19 at 22:04
  • @JohnnyWineShirt give me more open answer, why it so important, please – Serg Burlaka Feb 08 '19 at 22:07
  • Not a lot of sense in all these `get()`. User still can cast data to MutableLiveData outside the DataViewModel and do whatever he wants. – ror Aug 14 '20 at 14:04

3 Answers3

7

It's a practice designed to restrict modification of the value from outside the class.

LiveData is read-only. MutableLiveData, as the name implies, allows one to change the value it holds.

If you expose a MutableLiveData directly, like in your second example, any code which can access that data field could also modify the value it holds.

Exposing the ability to change data's content from outside DataViewModel class could make it harder to debug and reason about where data's content is coming from at any given time.

jensck
  • 154
  • 1
  • 11
5

MutableLiveData is essentially a LiveData with public access to two methods setValue() and postValue() for modifying that data.

Therefore, MutableLiveData is needed if you plan to modify the values of the LiveData.

However, in programming, it's a common concept to make your variables immutable or restrict the access of those who can modify the data of an object. You wouldn't want to expose the ability to modify the contents of variables within an object if there's no need to do so.

Therefore, for MutableLiveData, we normally use a getter to get it's parent form, which is LiveData.

By getting only LiveData, we can ensure that those who access the LiveData object can only read the values stored within with no ability to change them.

In a sense, it's just the concept of why you should use private variables with getters.

Jackey
  • 3,184
  • 1
  • 11
  • 12
1

LiveData is immutable. In LiveData the methods of setValue() and postValue() are not public and data is just read-only, whereas MutableLiveData is LiveData which is mutable and can access to change the data. In addition when defines var data = MutableLiveData<Int>() allowing public access to a variable that it can't consider 'Encapsulation' subject, but in

private var count = MutableLiveData<Int>()
    val countValue : LiveData<Int>
    get() = count

we define a public value of LiveData for sharing purposes so that it is able to get the value of “count” as the value of that live data.