LiveData in Kotlin
LiveData is used to get real-time updates from activities, fragments, or services. The LiveData only notifies the activity or fragment about an update if they are in a Started or Resumed lifecycle state. The ability of LiveData to understand the lifecycle of the app components makes LiveData so powerful.
Benefits
There are a bunch of benefits that come with using LiveData, I will be only mentioning some of them. LiveData reduces memory leaks because it knows when the activity or fragment is destroyed and removes the observer. LiveData also helps the UI data be up to date by notifying it of any data changes. LiveData also works very well with configuration changes that happen, like a screen rotation.
Getting Started
Let’s start by creating a simple app that implements a number every time you click on the button. First, create a new project in Android Studio. Then enable view binding. To do this, open the build.gradle file and add this inside the android tab.
viewBinding {
enabled = true
}
Next we want to open up the acitivty_main.xml file and add a text view and a button. The text view will be used to show the number of times the button has been clicked. Your activity_main.xml file should look like this.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/number_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:textSize="75sp"
android:textAlignment="center" />
<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/number_text_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"
android:text="Add" />
</androidx.constraintlayout.widget.ConstraintLayout>
Then create a new class called MainViewModel.kt, this is where you will be creating the LiveData. Your code in MainViewModel.kt will look like this.
class MainViewModel : ViewModel() {
private val _numberOfTaps = MutableLiveData<Int>(0)
val numberOfTaps = _numberOfTaps
fun addNumber() {
_numberOfTaps.value = _numberOfTaps.value?.plus(1)
}
}
We created a private variable named _numberOfTaps so we can update the value of the LiveData inside MainViewModel. We also created another variable called numberOfTaps, which is equal to _numberOfTaps. You may be wondering why we did this. This is so we can call on numberOfTaps outside of MainViewModel and not change the value of numberOfTaps outside of MainViewModel. The function addNumber() is called when we hit the “ADD” button.
Lastly, open up MainActivity.kt and set up view binding. We also need to create an instance of mainViewModel to be able to work with the LiveData. This is how the code in MainActivity.kt should look.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
mainViewModel.numberOfTaps.observe(this) { numberOfTaps ->
binding.numberTextView.text = numberOfTaps.toString()
}
binding.addButton.setOnClickListener {
mainViewModel.addNumber()
}
}
}
We set up an observer for numberOfTaps because we want the UI to watch any changes in data and update the text view. Run the app and you should be able to click the add button and watch the number increase automatically.
Conclusion
This is a very simple app but it’s just to show you an example of how LiveData works. I hope that you learned something from this and that you can research more of what LiveData can do!