Search code examples
androidkotlinandroid-livedataencapsulation

How LiveData encapsulation works in AndroidStudio and Kotlin?


I am working on a project and I have ViewModel and using LiveData with encapsulation.

private val _counter = MutableLiveData<Int>()
val counter: LiveData<Int>
    get() = _counter

On activity side I observe counter from ViewModel.

viewModel.counter.observe(this, Observer {
    binding.clickCounterText.text = it.toString()
})

In ViewModel I only work with _counter, but counter observer knows that _counter have been changed? HOW IT WORKS? How is counter changed when _counter is changed?

Please can someone explain it to me? Thanks


Solution

  • The counter is upcasting of _counter because of _counter is a MutableLiveData and MutableLiveData is a subclass of LiveData. When the Activity invoking the counter it actually gets the reference of _counter, so when the Activity observes the counter it is actually observing the _counter.