Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda