1

I have view model and I use live data in encapsulation, which one is recommended to use and why?

private val _licenseStatusFromWebService = MutableLiveData<String?>()
val licenseStatusFromWebService: LiveData<String?> = _licenseStatusFromWebService 

private val _licenseStatusFromWebService = MutableLiveData<String?>()
val licenseStatusFromWebService: LiveData<String?>
    get() = _licenseStatusFromWebService
Kanan
  • 203
  • 1
  • 15

3 Answers3

2

It Does not matter which way you use it as long as the MutableLiveData you are referring to is a val and not a var, but if you are going to modify or reassign the MutableLiveData to something else the getter approach get() = will return the latest instance and equals approach = will return the initial instance.

Also, Kotlin internally builds a getter for every property you have so if you are choosing the equals approach = for the sole purpose of reducing code on production, it will amount to nothing.

  • You mean that if Mutable Live Data is val it doesnt matter, but if it is var, I must use get() – Kanan Jan 05 '23 at 10:11
  • yes, but as you mentioned in other comments developer.android website has get() because if you keep using get() it won't matter even when you mistakenly reassign the said object. It is generally a best practice to use get() when typecasting an object to prevent getting older instances. – sushant sangle Jan 05 '23 at 10:18
  • Thanks for reply, I thinks it can be correct answer. – Kanan Jan 05 '23 at 10:27
  • I have second question https://stackoverflow.com/questions/75017024/which-one-recommended-to-use-postvalue-in-io-thread-or-setvalue-on-main-thre – Kanan Jan 05 '23 at 10:30
0

I think using an object directly is recommended way in ViewModel

private val _licenseStatusFromWebService = MutableLiveData<String?>()
val licenseStatusFromWebService: LiveData<String?> = _licenseStatusFromWebService

because, I am using this approach in some of my projects

Chirag Thummar
  • 665
  • 6
  • 16
0

It`s just to encapsulate mutable LiveData from immutable. As in UI you should use already prepared data from ViewModel to avoid modifying it from the UI directly.

private val _licenseStatusFromWebService = MutableLiveData<String?>()
val licenseStatusFromWebService: LiveData<String?> = _licenseStatusFromWebService

Yurii
  • 552
  • 3
  • 14
  • But in developer.android site, they used get() function but not explain why. – Kanan Jan 05 '23 at 10:06
  • it is the same, it depends on your code style, in these two cases you will get the reference to the same object. – Yurii Jan 05 '23 at 10:27