Kotlin / Kotlin for Android Development

Using LiveData and ViewModel in Kotlin

This tutorial will introduce you to LiveData and ViewModel, two key architectural components used in Android development with Kotlin. You'll learn how to manage and observe UI-rel…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces using Kotlin in Android applications and building modern UIs.

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

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help