Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda