Using LiveData and ViewModel in Kotlin

Tutorial 3 of 5

Introduction

In this tutorial, we will be working with LiveData and ViewModel, two crucial components of the Android Architecture Components in Kotlin. We'll explore how they can be utilized to manage and observe UI-related data in an efficient way.

Goals
- Understand LiveData and ViewModel
- Learn how to use LiveData and ViewModel in Kotlin

What you will learn
By the end of this tutorial, you will be able to:
- Define LiveData and ViewModel
- Implement LiveData and ViewModel in a simple Android app

Prerequisites
- Basic understanding of Kotlin programming language
- Basic knowledge of Android development

Step-by-Step Guide

Concepts

ViewModel: This is a class that is designed to store and manage UI-related data in a lifecycle conscious way. It allows data to survive configuration changes such as screen rotations.

LiveData: LiveData is an observable data holder. It is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services.

Using ViewModel

  1. Create a class that extends ViewModel:
class MyViewModel : ViewModel() {
    // Your code here
}
  1. You can now use this ViewModel in your activity or fragment:
class MyActivity : AppCompatActivity() {

    private lateinit var model: MyViewModel

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

        model = ViewModelProvider(this).get(MyViewModel::class.java)
        // Now you can use the ViewModel
    }
}

Using LiveData

  1. In your ViewModel, create an instance of LiveData:
class MyViewModel : ViewModel() {
    val myLiveData: LiveData<String> = MutableLiveData()
}
  1. Observe the LiveData instance in your activity or fragment:
model.myLiveData.observe(this, Observer { myData ->
  // Update UI here
})

Code Examples

Example 1: Using ViewModel

// Example ViewModel
class ExampleViewModel : ViewModel() {
    var counter = 0 // this data will survive configuration changes
}

// Using ViewModel in an Activity
class ExampleActivity : AppCompatActivity() {

    private lateinit var model: ExampleViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        model = ViewModelProvider(this).get(ExampleViewModel::class.java)

        // Display the value of the counter
        textView.text = model.counter.toString()
    }
}

Example 2: Using LiveData

// Example ViewModel with LiveData
class ExampleViewModel : ViewModel() {
    val counter: LiveData<Int> = MutableLiveData()
}

// Using LiveData in an Activity
class ExampleActivity : AppCompatActivity() {

    private lateinit var model: ExampleViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        model = ViewModelProvider(this).get(ExampleViewModel::class.java)

        // Observe the LiveData
        model.counter.observe(this, Observer { count ->
            // Update UI
            textView.text = "$count"
        })
    }
}

Summary

In this tutorial, we learned about LiveData and ViewModel, two key architectural components in Android development with Kotlin. We looked at how to create and use them in our applications, and saw examples of how they can be implemented in code.

Practice Exercises

Exercise 1: Create a ViewModel that holds a LiveData of a List<String>. Observe this LiveData in an Activity and display the list in a TextView.

Exercise 2: Update the LiveData in the ViewModel whenever a button is pressed in the Activity. Observe the changes in the Activity.

Additional Resources