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

410
Visualizações
Why does LiveData better than MutableLiveData?

In many samples i see that:

 class DataViewModel{
         val data:LivaData<Int>
             get() = _data 

         private val _data = MutableLiveData<Int>()

    }

But more simply looks like this:

 class DataViewModel{
         val data = MutableLiveData<Int>()

    }

so, why need this more complicated code construction with 2 fields?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

It's a practice designed to restrict modification of the value from outside the class.

LiveData is read-only. MutableLiveData, as the name implies, allows one to change the value it holds.

If you expose a MutableLiveData directly, like in your second example, any code which can access that data field could also modify the value it holds.

Exposing the ability to change data's content from outside DataViewModel class could make it harder to debug and reason about where data's content is coming from at any given time.

over 4 years ago · Santiago Trujillo Relatório

0

MutableLiveData is essentially a LiveData with public access to two methods setValue() and postValue() for modifying that data.

Therefore, MutableLiveData is needed if you plan to modify the values of the LiveData.

However, in programming, it's a common concept to make your variables immutable or restrict the access of those who can modify the data of an object. You wouldn't want to expose the ability to modify the contents of variables within an object if there's no need to do so.

Therefore, for MutableLiveData, we normally use a getter to get it's parent form, which is LiveData.

By getting only LiveData, we can ensure that those who access the LiveData object can only read the values stored within with no ability to change them.

In a sense, it's just the concept of why you should use private variables with getters.

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