简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM