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?

This is more fundamental than just about live data. Basically, on all the languages that Kotlin compiles to, objects are passed by reference, and so what the encapsulation code does it that it simply returns a reference to the object that is stored in _counter whenever the get method of the property counter gets called. This means that what actually happens is that when you change the value property in _counter, you are changing the value property in the object that _counter references, which is the same exact object that counter references. Basically, there isn’t any magic going on under the hood, it’s just how the Kotlin works!

1 Like