Hey. In a Compose Codelab by <@U7BNG1JCF>, I came ...
# android
Hey. In a Compose Codelab by @Sean McQuillan [G], I came across this ViewModel class:
Copy code
class HelloCodelabViewModel: ViewModel() {

   // LiveData holds state which is observed by the UI
   // (state flows down from ViewModel)
   private val _name = MutableLiveData("")
   val name: LiveData<String> = _name

   // onNameChanged is an event we're defining that the UI can invoke
   // (events flow up from UI)
   fun onNameChanged(newName: String) {
       _name.value = newName

class HelloCodeLabActivityWithViewModel : AppCompatActivity() {
   val helloViewModel by viewModels<HelloCodelabViewModel>()

   override fun onCreate(savedInstanceState: Bundle?) {
       /* ... */

       binding.textInput.doAfterTextChanged {

       helloViewModel.name.observe(this) { name ->
           binding.helloText.text = "Hello, $name"
I have two questions. 1- Why is
not defined public so that it can be directly observed rather than through
? 2- How can
be modified using observe while it is defined as immutable (val)?
1. It’s for draw the line between something that is mutable (MutableLiveData) and not mutable (LiveData). In this case you can’t mutate the state from outside of the ViewModel (from Activity for example)