Example from Android Jetpack: LiveData
Last active
October 4, 2024 19:17
-
-
Save humblehacker/0eb6458b1df6cf3049e031f36f0615f5 to your computer and use it in GitHub Desktop.
Don't expose MutableLiveData
I find this method the best - mainly because less typing (better working code completion)
private val mutableLiveData = MutableLiveData<State>()
val liveData = _liveData.asLiveData()
fun <T> MutableLiveData<T>.asLiveData() = this as LiveData<T>
More ways here
"And also, it's exposing a MutableLiveData. Almost ... You should almost never do this." I'm not so sure about this, for one time shots, for example when wanting to show an error Toast or similar it's handy to have a public mutableLiveData(null) in your ViewModel which is observed in your activity, when you set the value the observer can show the error and then set the value to null, instead of calling another function of the ViewModel to reset the value which I would find to be too much of an overhead for nothing. And this is actually also being done in Google's codelab "Advanced Coroutines"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

Fantastic organization of best practice notes across various talks! This is exactly what I was looking for in terms of seeing more details after watching the 2018 Android Summit discussion, Fun with LiveData.
I understand the need for creating getter and setter points for LiveData in the ViewModel. However, I am looking to understand how the
get()syntax works.ie:
Here is a good explanation on Stackoverflow: How Does Android LiveData get() syntax work?