Search code examples
androidkotlinmvvmviewmodelandroid-livedata

which is recommended use getter or just equals in live data in view model android kotlin


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

Solution

  • 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.