Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of implementing LiveData

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?

like image 487
Johann Avatar asked May 20 '19 07:05

Johann


People also ask

In which method should you observe a LiveData object?

Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

How does LiveData work?

LiveData notifies Observer objects when there is any change occurs. No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed. No more manual lifecycle handling: UI components just observe relevant data and don't stop or resume observation.

What is live data and mutable live data in Android?

MutableLiveData is just a class that extends the LiveData type class. MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide.

When should I use LiveData?

As a rule of thumb, I would advise to use (or switch to) LiveData almost in every situation in which these other alternatives are considered (or were already used), and specifically, in every scenario in which we want to update the UI based on data changes in a clean, robust and reasonable manner.


1 Answers

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.

like image 192
ryan_rawlinson Avatar answered Oct 14 '22 00:10

ryan_rawlinson