0

To avoid exposing the MutableLiveData from ViewModel, there's a pattern to avoid only exposing the LiveData object instead. My question is, what's the difference between both approaches?

Attributing directly:

private val _value = MutableLiveData<Any>()
val value: LiveData<Any> = _value

Using the get()

private val _value = MutableLiveData<Any>()
val value: LiveData<Any>
    get() = _value
Selman Tosun
  • 428
  • 5
  • 14
Bruno Martins
  • 1,347
  • 2
  • 11
  • 32
  • You can only modify the content of `LiveData` objects within the class they reside it. Their difference only comes in play when we talk about encapsulation paradigm. – Taseer Jun 10 '19 at 16:51
  • Ok, but what's the difference? I know the reason for what it is used for. – Bruno Martins Jun 10 '19 at 16:53
  • @CommonsWare this is not duplicated – Bruno Martins Jun 10 '19 at 16:54
  • `MutableLiveData` as the name suggests allows you to mutate its content. This exposes public get/set methods while the LiveData does not. – Taseer Jun 10 '19 at 16:55
  • The question and answer from the duplicate certainly seem to cover what you are asking. If you have additional concerns, what are they? – CommonsWare Jun 10 '19 at 16:59
  • Both approaches are attributing the value from a MutableLiveData to a LiveData, what I'd like to know if there's any difference between both – Bruno Martins Jun 10 '19 at 16:59
  • 1
    That is covered in the question and the answer from the duplicate. The question literally shows you the difference, in terms of the generated Java code. The answer explains the rationale behind the two approaches. – CommonsWare Jun 10 '19 at 17:12

0 Answers0