Reputation: 29867
In the Android docs it shows an example creating a LiveData object as follows:
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
But I have seen code elsewhere that shows it like this:
val currentName: MutableLiveData<String> = MutableLiveData()
Both of these are located in the viewmodel. In the second example, the LiveData model is instantiated when the class is created whereas in the first example, it is only instantiated when the object is first used.
Are both of these cases valid?
Upvotes: 6
Views: 3579
Reputation: 76
Yes, both of these cases are valid. However, there is a distinct difference between the two. When using by lazy
it will still set the LiveData object, but it will not set it until the variable is first used. In the case of the second option, it will initialize the LiveData object when parent is created.
Upvotes: 6