1

Help me out please.
I want to observe some String using LiveData.
OnChanged() getting triggered once upon app start, but when Im changing the value of string1 by button click, onChange() does not trigger and information is not updated. TextView keeps showing "Wow"
I do everything exactly as described here.
The ViewModel:

class CurrentViewModel : ViewModel() {


val currentName: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
}
}

The Fragment:

class CurrentFragment : Fragment(R.layout.current_fragment) {
        private val viewModel: CurrentViewModel by viewModels()
       var string1 = "Wow!"

  override fun onActivityCreated(savedInstanceState: Bundle?)
       val nameObserver = Observer<String> { newName ->
            textview.text = newName        }
       viewModel.currentName.value = string1
       viewModel.currentName.observe(activity!!, nameObserver)


   button.setOnClickListener {
            string1 = "some new string"
        }
}
Pedro Massango
  • 4,114
  • 2
  • 28
  • 48
Waldmann
  • 1,563
  • 12
  • 25
  • 1
    I think you forgot to update the `LiveData` to change value. According document you mention, you must call the `setValue(T)` method to update the LiveData object from the main thread. If the code is executed in a worker thread, you can use the `postValue(T)` method instead to update the LiveData object. You need to add a syntax to update the `LiveData` in `button` action. – mixin27 Feb 20 '20 at 03:01

1 Answers1

5

You are not updating the value of viewModel.currentName you should always update the MutableLiveData's value to notify the observers.

Inside of your OnClickListener do:

button.setOnClickListener {
    // update viewModel value to notify listeners/observers
    viewModel.currentName.value = "some new string"
}

Obs: You can remove string1 as it is useless!

Pedro Massango
  • 4,114
  • 2
  • 28
  • 48
  • Thank you. But if I must update `LiveData` manually each time then why do I need `LiveData` at all? I can just update the UI directly instead. Instead of `viewModel.currentName.value = "some new string"` I write `textview.text = "some new string"`, right? It is even shorter =\ – Waldmann Feb 20 '20 at 05:51
  • 1
    @Waldmann Because `LiveData` gives `Ensures your UI matches your data state`, `No memory leaks`, `No crashes due to stopped activities, `No more manual lifecycle handling`, `Always up to date data`, `Proper configuration changes` and `Sharing resources`. You can find these advantages at official document at [here](https://developer.android.com/topic/libraries/architecture/livedata). – mixin27 Feb 20 '20 at 10:07