import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import android.widget.Button
import android.widget.TextView
class LiveDataDemoActivity : AppCompatActivity() {
private val numberLiveData = MutableLiveData<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_live_data_demo)
val numberTextView = findViewById<TextView>(R.id.numberTextView)
val incrementButton = findViewById<Button>(R.id.incrementButton)
numberLiveData.value = 0
numberLiveData.observe(this) { number ->
numberTextView.text = "Number: $number"
}
incrementButton.setOnClickListener {
val current = numberLiveData.value ?: 0
numberLiveData.value = current + 1
}
}
}We start by setting the initial value of numberLiveData to 0. Then, we observe this LiveData from the Activity, so whenever the number changes, the numberTextView updates automatically. The button click listener increases the current number by 1 and updates the LiveData, triggering the UI update. This shows how LiveData keeps UI and data in sync easily.