Home > Software design >  Why should I double declare a variable in a ViewModel class when using LiveData?
Why should I double declare a variable in a ViewModel class when using LiveData?

Time:10-14

Right now I am following a tutorial where I am developing a simple game app trying to understand and use MVVM app architecture. In my ViewModel class I have a field which contains the score of the player.

The score variable is declared like this:

private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
    get() = _score

Now, in my UI Controller class, I observe the score like this:

viewModel.score.observe(this, Observer { newScore ->
        binding.scoreText.text = newScore.toString()
    })

So, my question is why do I need the second declaration of score? Can't I just have a

val score = MutableLiveData<Int>()

and observe it like above? I tried and it works.

CodePudding user response:

It will work. The point of doing that is to make sure that changes to that variable only occurs from one place, being your ViewModel. It's just a pattern people have followed to make it easier for you to debug and ensure that state of your app/view is correct. One source from Google I found here, although I'm sure there are plenty more

  • Related