How Does Android LiveData get() syntax work?

livedata observer not called
android livedata tutorial
convert livedata to mutablelivedata
viewmodel and livedata (android)
livedata setter is protected
android livedata remove observer
cannot access setvalue livedata
initialize livedata

I understand the need for creating getter and setter points for LiveData in the ViewModel, but I'm looking to understand how the get() syntax works in Android.

ie:

val isRealtime: LiveData<Boolean>
    get() = _isRealtime
private val _isRealtime = MutableLiveData<Boolean>()

get() is not related to Android.

val isRealtime: LiveData<Boolean>
    get() = _isRealtime

Here, get() is overriding the automatically-generated Kotlin getter function for the isRealtime property. So, instead of returning its own value, it returns the value of _isRealtime.

Personally, I recommend simpler syntax:

private val _isRealtime = MutableLiveData<Boolean>()
val isRealtime: LiveData<Boolean> = _isRealtime

The objective of either of these is to keep the mutability private, so consumers of this class do not accidentally update the MutableLiveData themselves.

How Does Android LiveData get() syntax work?, 3 Answers. get() is not related to Android. Here, get() is overriding the automatically-generated Kotlin getter function for the isRealtime property. So, instead of returning its own value, it returns the value of _isRealtime . Four basic steps to work with LiveData. In order to use LiveData in your project, all you need to do is follow the below four steps: Firstly, for holding the data, you need to create a LiveData instance in your ViewModel. After creating the instance of LiveData, you need to set the data in the LiveData by using methods like setValue and postValue.

I wrote a util function for this logic:

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import kotlin.reflect.KProperty

fun <T> immutable(data: MutableLiveData<T>): Immutable<T> {
    return Immutable(data)
}

class Immutable<T>(private val data: MutableLiveData<T>) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): LiveData<T> {
        return data
    }
}

Then you can use in any of your ViewModel as:

private val _counter: MutableLiveData<Int> = MutableLiveData()    
val counter: LiveData<Int> by immutable(_counter)

or in short:

private val _counter = MutableLiveData<Int>()    
val counter by immutable(_counter)

LiveData, The android.arch Architecture Components packages are no longer In addition , LiveData has onActive() and onInactive() methods to get� Now, I will demonstrate how to implement LiveData in Android application. In this LiveData android example, we use Retrofit2 for Rest API calling and will fetch data from a remote server and display it on RecyclerView with the help of ViewModel and LiveData.

In Kotlin we have multiple ways of exposing live data from ViewModel to the view.

class MyViewModel: ViewModel() {

    // Solution 1 - make MutableLiveData public
    // This approach works, but this is a bad idea because
    // view can modify the LiveData values
    val liveDataA1 = MutableLiveData<State>()

    // Solution 2 - let's make LiveData public (expose it instead of MutableLiveData)
    // Now from view perspective this solution looks fine, bu we have a problem,
    // because we need MutableLiveData within ViewModel to put/post new values to
    // the stream (we can't post values to LiveData).
    val liveDataA2 = MutableLiveData<State>() as LiveData<State>

    // Let's capture our requirements:
    // 1. We need to expose (immutable) LiveData to the view,
    // so it cannot edit the data itself.
    // 2. We need to access MutableLiveData from ViewModel to put/post new values.
    // Now, let's consider few appropriate solutions

    // Solution 3
    // Let's name mutable live data using underscore prefix
    private val _liveData3 = MutableLiveData<State>()
    val liveData3 = _liveData3 as LiveData<State>

    // Solution 4
    // We can also perform casting by specifying type for a variable
    // (we can do it because MutableLiveData extends LiveData)
    private val _liveData4 = MutableLiveData<State>()
    val liveData4: LiveData<State> = _liveData4

    // Solution 5
    // Starting from Kotlin 1.4-M.2 we can delegate call to another property
    private val _liveData5 = MutableLiveData<State>()
    val liveData5 by this::_liveData5

    // Solution 6
    // These above solutions work quite well, but we could do even better by
    // defining custom asLiveData extension function.
    private val _liveData6 = MutableLiveData<State>()
    val liveData6 = _liveData6.asLiveData()

    fun <T> MutableLiveData<T>.asLiveData() = this as LiveData<T>
    // Amount of code is similar, but notice that this approach works much better
    // with code completion.

    // Solution 7 (IMO Best)
    // We can also use alternative naming convention - use "mutableLiveData"
    // as variable for mutable live data instead of using underscore prefix
    private val mutableLiveData7 = MutableLiveData<State>()
    val liveData7 = mutableLiveData7.asLiveData()

    // BTW
    // We could also expose getLiveData8() method, but liveData is a state not an action.

    // Solution 9
    // This does not create backing field for the property
    // (more optimised but still Solution 7 is easier to use)
    private val _liveData9 = MutableLiveData<State>()
    val liveData9 get() = _liveData9 as LiveData<State>
}

LiveData Overview, You can also use observeForever() to observe LiveData without a getValue() will return the value of LiveData at the moment the method gets called. You have to use setValue() when you are working on the mainThread. implementation "android.arch.lifecycle:extensions:${architectureVersion}". LiveData is a data holder class that can be observed within a given lifecycle. This means that an Observer can be added in a pair with a LifecycleOwner, and this observer will be notified about modifications of the wrapped data only if the paired LifecycleOwner is in active state.

Learn how to use LiveData – JensKlingenberg.de, Learn how to choose between LiveData and Flow. What you'll need. Android Studio 3.5 or above. The codelab may work with other versions, but some things � Here is a good explanation on Stackoverflow: How Does Android LiveData get() syntax work? get() is not related to Android. val isRealtime: LiveData<Boolean> get() = _isRealtime Here, get() is overriding the automatically-generated Kotlin getter function for the isRealtime property. So, instead of returning its own value, it returns the value of _isRealtime. Personally, I recommend simpler syntax: private val _isRealtime = MutableLiveData<Boolean>() val isRealtime: LiveData<Boolean> = _isRealtime

Learn advanced coroutines with Kotlin Flow and LiveData, Example from Android Jetpack: LiveData Here is a good explanation on Stackoverflow: How Does Android LiveData get() syntax work? Photo by Chris Liverani on Unsplash. Let’s look at the definition from Android’s documentation:. LiveData is an observable data holder class.Unlike a regular observable, LiveData is lifecycle

Don't expose MutableLiveData � GitHub, MVC, MVP and MVVM are some of the Architecture patterns used by Google has introduced android architecture components which includes Each component does single and unique Job, which is why it is public LiveData< News> getObservableProject() { .get(NewsViewModel.class);viewModel. So, the basic idea is to have efficient communication between the data and the UI of the application and we all know that the best way to do this is by using LiveData which is a part of Android Jetpack. The most commonly used methods of LiveData is setvalue and postValue. By name, these two functions are quite confusing i.e. it seems that both

Comments
  • Tried reading kotlin docs on functions yet?
  • Yes, but it's been a couple of years. I'll check that out. Thanks for the tip @MarcinOrlowski!
  • Thank you for sharing the simpler syntax @CommonsWare! It's good to know I don't need to explicitly state the get().
  • @AdamHurwitz: get() has its uses, but for more complex scenarios. For example, one pattern in Android is to create private extension properties on Intent for extras or on Bundle for fragment arguments. There, you would override get() and set() on the extension properties to route to the proper getters/setters (e.g., getString() and putString() on a Bundle). For a simple case like this, though, that seems like overkill.
  • Also, an organizational advantage of keeping get() is it allows you to define all of the public variables at the top of the ViewModel class.
  • I really like solution #5. Unfortunately can't use it yet in Android. BTW I think the this::_liveData5 can actually be just liveData5
  • Nope, it cant. Somehow the this:: is needed