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…
Section overview
5 resourcesIntroduces 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
- Create a class that extends ViewModel:
class MyViewModel : ViewModel() {
// Your code here
}
- 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
- In your ViewModel, create an instance of LiveData:
class MyViewModel : ViewModel() {
val myLiveData: LiveData<String> = MutableLiveData()
}
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article