0

Inside main activity, i cannot call getValue() on a MutableLiveData attribute of a ViewModel; however, i can inside the ViewModel class. What is the reason for this?

Example code: Main Activity -

noodleViewModel = ViewModelProviders.of(this).get(NoodleViewModel.class);
        noodleViewModel.indexOfItemSelected.observe(this, index ->
            {
                Toast.makeText(this, String.format("This is the index: %d", index.intValue()), Toast.LENGTH_SHORT).show();

        );

Inside ViewModel class -

   public int getPosition() {
        return indexOfItemSelected.getValue();
    }

1 Answers1

1

You are already observing your LiveData, so index parameter of your lambda is already the value you are looking for

noodleViewModel.indexOfItemSelected.observe(this, index -> {
    index == noodleViewModel.indexOfItemSelected.getValue() // should return true
}
John Joe
  • 12,412
  • 16
  • 70
  • 135
Dmitrii Leonov
  • 1,331
  • 1
  • 15
  • 25