Kotlin backing property in Android ViewModel - android

Was just wondering, why is it better to use backing property for MutableLiveData, instead of just exposing getter function that returns the MutableLiveData property as live data. For example:
Why this code
private val _registeredDevicesObservable: MediatorLiveData<List<Data>> = MediatorLiveData()
val registeredDevicesObservable: LiveData<List<Data>> = _registeredDevicesObservable
is better or more acceptable than this one
private val _registeredDevicesObservable: MediatorLiveData<List<Data>> = MediatorLiveData()
fun registeredDevicesObservable(): LiveData<List<Data>> = _registeredDevicesObservable
As also when this getter function is keeping the LiveData immutability and keeps me from having that little annoying underscore syntax when accessing the property inside the view model.

It's just less idiomatic in the language to use a function that simply returns an already-available object. You're free to do it any way you like, but if others have to work with your code, it will be easier to understand and work with if you follow general conventions.
There isn't as strong a convention about whether the backing property should have a leading underscore in the name, so if you don't like it, don't use it.
One reason to stick with these conventions is there is a proposed upcoming language feature to allow you to do this without a backing property, and so if you're following the conventions, it will be very easy to update your code to eliminate the backing property.

Related

Why does the properties inside a kotlin class must be initialized on the other hand java allows me to do it

The following code shows up "Property must be initialized or be abstract" error.I understand that I can use lateinit in such cases but I wanted to know the reason behind the restriction .
class Student{
val s:String
}
In the case of a non-nullable property like in your example, the reason is necessity. Java implicitly gives member variables a value of null. In Kotlin, a non-nullable property cannot have a value of null, so you have to give it an instance of something to be the starting value.
But even if you declared it as nullable String?, Kotlin will require you to specify the starting value. Kotlin avoids making implicit assumptions about the intent of your code. Kotlin's design goals are to make code more readable and robust. The designers have done research on common causes of bugs in other languages, and have made Kotlin more restrictive in areas that have been frequent sources.

ViewBinding - Does exposing views through get() cause a performance issue?

Recently I migrated my project to ViewBinding and as a way to make it less verbose, I decided to expose it through get() property and it seems to be working fine, but some other developers are saying that it may cause memory issues because it's assigning a value to a variable, which I think it's not doing this, since it's exposing through the get() property. Example:
class MyActivity : AppCompatActivity() {
private val textView: TextView get() = binding.textViewID
private val binding by lazy { MyActivityBinding.inflate(layoutInflater) }
}
can someone confirm this?
When you define a property with a getter and no initial assignment, there is no backing field generated. So no, this is not wasting memory.
The way you wrote it on one line looks very similar to code where there is no getter defined and you are assigning an initial value to a backing field. Maybe your colleagues misread your code. I usually define getters on the next line so it looks distinct. Otherwise, it is easy to accidentally omit get() when you intended to include it.
Even if it were creating a backing property, surely you don't have enough views referenced that it would even approach an amount of memory use that you should waste your time worrying about it.

LiveData confusion in [Android] Plaid App

I am referring to the Plaid open source project on github Link to Plaid
It is an excellent source to learn new techniques on Android.
As I was going through the code, I came across a certain style of coding around LiveData which I really didn't understand. If anybody can help me get it.
Here goes:
There's a ViewModel(vm) with this piece of code:
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>>
get() = _openLink
Fairly simple? Note that, there are 2 variables here: openLink and _openLink. The getter for openLink is returning the _openLink LiveData.
In the activity they observe the openLink LiveData as follows:
viewModel.also { vm ->
vm.openLink.observe(this, EventObserver { openLink(it) })
..... // Other stuff
}
Now, the other livedata _openLink is being called by the UI supposedly on a button click and it's defined like this:
fun viewShotRequested() {
_shotUiModel.value?.let { model -> // ignore this part
_openLink.value = Event(model.url) // setValue on _openLink
}
}
So here my understanding is, on setValue() on _openLink, EventObserver{openLink(it)} will get called.
My question is, why have they done it like this?
Questions:
Why not observe directly on _openLink?
Will it not have the same effect? What am I missing here?
_openLink is mutable. You must always expose something which is immutable and cannot be changed by your observer, because that should only be done by your ViewModel, even though exposing _openLink would have no effect.
That's why you need to expose openLink which is immutable.
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>> = _openLink
The MutableLiveData property shouldn't be exposed: it is mutable and could be changed anywhere across your program.
That's why the LiveData is exposed instead: it is responsible for updating your property, and it uses the MutableLiveData as a backing field.
The exception to this would be two-way DataBinding, where direct access to the value would be needed.
My question is, why have they done it like this?
Because Google apparently enjoys writing more code for the sake of writing more code.
The supposed answer if you're inclined to believe them is that LiveData<Event<T>> is preferred over SingleLiveData because they came up with it later than with LiveData<Event<T>> and is therefore supposedly better.
They intend to use an "enqueueable event-bus that forgets items after it is emitted to at least 1 observer", but Jetpack offers no such concept out of the box, personally I had to write one of my own.
Even so, there's a distinction between whether you can write into something, and whether you can only read from something but not write into it yourself. In this case, only the ViewModel wants to be able to emit events, so it is the ViewModel that holds a Mutable__ reference, but exposes a regular LiveData to the outside world (in my case, EventEmitter vs EventSource).
As for the _, it's a Kotlin style convention that will hopefully be changed one day, as you could either do:
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>>
get() = _openLink
But you could also do
private val openLink = MutableLiveData<Event<String>>()
fun openLink(): LiveData<Event<String>> = openLink
And that way we could ditch the _ prefix in our own code, but for some reason the authors of Kotlin hadn't come up with that convention in time.

Why does LiveData better than MutableLiveData?

In many samples i see that:
class DataViewModel{
val data:LivaData<Int>
get() = _data
private val _data = MutableLiveData<Int>()
}
But more simply looks like this:
class DataViewModel{
val data = MutableLiveData<Int>()
}
so, why need this more complicated code construction with 2 fields?
It's a practice designed to restrict modification of the value from outside the class.
LiveData is read-only.
MutableLiveData, as the name implies, allows one to change the value it holds.
If you expose a MutableLiveData directly, like in your second example, any code which can access that data field could also modify the value it holds.
Exposing the ability to change data's content from outside DataViewModel class could make it harder to debug and reason about where data's content is coming from at any given time.
MutableLiveData is essentially a LiveData with public access to two methods setValue() and postValue() for modifying that data.
Therefore, MutableLiveData is needed if you plan to modify the values of the LiveData.
However, in programming, it's a common concept to make your variables immutable or restrict the access of those who can modify the data of an object. You wouldn't want to expose the ability to modify the contents of variables within an object if there's no need to do so.
Therefore, for MutableLiveData, we normally use a getter to get it's parent form, which is LiveData.
By getting only LiveData, we can ensure that those who access the LiveData object can only read the values stored within with no ability to change them.
In a sense, it's just the concept of why you should use private variables with getters.

ViewModel backing properties [kotlin]

Looking to the code of some Google's demo app (like sunflower or Google io 2018 app) and I've noticed that for the viemodels' backing properties they use a separate instance of the same type with a custom getter; like this:
private val _userData: MutableLiveData<User>
val userData: LiveData<User>
get() = _userData
but why do they do that? Isn't better to directly make the _userData accessible?
Could it be because while _userData is a MutableLiveData they don't want the observer to be able to change the value?
userData which is exposed to the Activity or Fragment must be immutable since the view only needs to observe to the LiveData. So, we need to make the actual _userData returns a LiveData.
One way is using the Kotlin coding convention and create two variables, _userData and userData, one is mutable and another one is not:
If a class has two properties which are conceptually the same but one
is part of a public API and another is an implementation detail, use
an underscore as the prefix for the name of the private property.

Categories

Resources