Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Why should I double declare a variable in a ViewModel class when using LiveData?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!