LiveData

13 Mar 2023 . android .


Advantages

  • No memory leaks

    Observers are cleaned up when their associated lifecycle is destroyed.

  • No crashes due to stopped activities

    If the observer is inactive, such as an activity in the back stack, it doesn’t receive any LiveData events.

  • Always up to date data

    Receive the latest data upon becoming active again.

Work with LiveData objects

Create LiveData object

Create an instance of LiveData to hold a certain type of data.

class NameViewModel : ViewModel() {

    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    // Rest of the ViewModel...
}

Observe LiveData object

Create an Observer object that defines the onChanged() method, which controls what happened when the LiveData object’s held data changes.

Attach the Observer object to the LiveData object using the observe() method.

class NameActivity : AppCompatActivity() {

    private val model: NameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Other code to setup the activity...

        // Create the observer which updates the UI.
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            nameTextView.text = newName
        }

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        model.currentName.observe(this, nameObserver)
    }
}

Update LiveData object

When you update the value stored in the LiveData object, the UI automatically updates in response.

button.setOnClickListener {
    val anotherName = "John Doe"
    model.currentName.setValue(anotherName)
}