LiveData helps your app update the screen automatically when data changes. It keeps your app data fresh and in sync with the UI without extra work.
0
0
LiveData basics in Android Kotlin
Introduction
When you want your app screen to update automatically after data changes.
When you want to avoid manual UI updates and keep data and UI connected.
When you want to observe data changes safely respecting the app lifecycle.
When you want to share data between different parts of your app easily.
Syntax
Android Kotlin
val liveData = MutableLiveData<Type>()
liveData.observe(lifecycleOwner) { data ->
// update UI with data
}
liveData.value = newValueMutableLiveData lets you change the data.
observe watches for data changes and updates UI safely.
Examples
Creates LiveData holding a String, sets initial value, and updates a TextView when data changes.
Android Kotlin
val liveData = MutableLiveData<String>()
liveData.value = "Hello"
liveData.observe(this) { text ->
textView.text = text
}Observes an integer LiveData in a fragment and updates UI when the number changes.
Android Kotlin
val liveData = MutableLiveData<Int>()
liveData.observe(viewLifecycleOwner) { number ->
numberText.text = number.toString()
}
liveData.value = 10Sample App
This simple app shows a TextView that updates automatically when LiveData changes. It starts by showing "Welcome to LiveData!".
Android Kotlin
class MainActivity : AppCompatActivity() { private val liveData = MutableLiveData<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val textView = TextView(this) setContentView(textView) liveData.observe(this) { text -> textView.text = text } liveData.value = "Welcome to LiveData!" } }
OutputSuccess
Important Notes
LiveData respects the lifecycle of your activity or fragment, so it only updates UI when the screen is visible.
Use MutableLiveData when you want to change data, and LiveData when you only want to observe.
Always observe LiveData with a lifecycle owner to avoid memory leaks.
Summary
LiveData holds data that UI can observe and update automatically.
Use MutableLiveData to change data and observe to watch changes.
LiveData updates UI safely respecting app lifecycle.