0
0
Android-kotlinHow-ToBeginner ยท 4 min read

How to Use LiveData in Android: Simple Guide with Examples

In Android, LiveData is a lifecycle-aware observable data holder that updates UI components automatically when data changes. You create a LiveData object in a ViewModel and observe it in your Activity or Fragment to react to data updates safely and efficiently.
๐Ÿ“

Syntax

LiveData is declared as a data holder that can be observed. Typically, you use MutableLiveData inside a ViewModel to update data, and expose it as LiveData to the UI.

Key parts:

  • MutableLiveData<T>: Mutable data holder you can change.
  • LiveData<T>: Read-only observable data.
  • observe(): Method to watch data changes from UI components.
kotlin
class MyViewModel : ViewModel() {
  private val _data = MutableLiveData<String>()
  val data: LiveData<String> = _data

  fun updateData(newValue: String) {
    _data.value = newValue
  }
}

// In Activity or Fragment
viewModel.data.observe(this) { value ->
  // update UI with value
}
๐Ÿ’ป

Example

This example shows a simple ViewModel with LiveData holding a string. The Activity observes this data and updates a TextView when the data changes.

kotlin
class MyViewModel : ViewModel() {
  private val _text = MutableLiveData<String>("Hello LiveData")
  val text: LiveData<String> = _text

  fun changeText(newText: String) {
    _text.value = newText
  }
}

class MainActivity : AppCompatActivity() {
  private lateinit var viewModel: MyViewModel

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val textView = TextView(this)
    setContentView(textView)

    viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

    viewModel.text.observe(this) { newText ->
      textView.text = newText
    }

    // Simulate data change after 2 seconds
    Handler(Looper.getMainLooper()).postDelayed({
      viewModel.changeText("LiveData Updated")
    }, 2000)
  }
}
Output
Initially shows: Hello LiveData After 2 seconds updates to: LiveData Updated
โš ๏ธ

Common Pitfalls

Common mistakes when using LiveData include:

  • Updating LiveData from a background thread using value instead of postValue().
  • Not observing LiveData with a proper lifecycle owner, causing memory leaks or no updates.
  • Exposing MutableLiveData directly to UI, which breaks encapsulation.
kotlin
class WrongViewModel : ViewModel() {
  val data = MutableLiveData<String>() // Exposed mutable directly

  fun updateWrong() {
    Thread {
      data.postValue("Wrong update from background") // Fixed to use postValue
    }.start()
  }
}

// Correct way:
class CorrectViewModel : ViewModel() {
  private val _data = MutableLiveData<String>()
  val data: LiveData<String> = _data

  fun updateCorrect() {
    Thread {
      _data.postValue("Safe update from background")
    }.start()
  }
}
๐Ÿ“Š

Quick Reference

Remember these tips when using LiveData:

  • Use MutableLiveData inside ViewModel to change data.
  • Expose only LiveData to UI to keep data safe.
  • Observe LiveData with lifecycle owners like Activity or Fragment.
  • Use postValue() for background thread updates, value for main thread.
โœ…

Key Takeaways

LiveData is lifecycle-aware and updates UI automatically when data changes.
Always expose LiveData as read-only to UI and use MutableLiveData inside ViewModel.
Observe LiveData with a lifecycle owner to avoid memory leaks and crashes.
Use postValue() to update LiveData from background threads safely.
LiveData helps keep UI and data logic clean and reactive.