Context
Using MutableLiveData<List<Integer>>
to hold a values. When the first value (using first value as example for brevity) in the List
is incremented, TextView
should update in onChanged
to display the first value in the List
.
Goals
- Increment first value in a
List
- Update
TextView
when first item of aList
changes
Problem
- On
Button
click, the first value in theList
is incremented butMutableLiveData.onChanged()
isn't called, why is this? - Does
MutableLiveData
only respond to itssetValue
method? - Could this be solved via the
List
containingMutableLiveData
Integers (i.e.,MutableLiveData<List<MutableLiveData<Integer>>
, problematic since requires listeners for each item in theList
)? - Is there a better way to achieve the goals?
Code
final MutableLiveData<List<Integer>> vals = new MutableLiveData<>();
List<Integer> intVals = new ArrayList<>();
intVals.add(0);
vals.setValue(intVals);
tv.setText("" + vals.getValue().get(0));
vals.observe(this, new Observer<List<Integer>>() {
@Override
public void onChanged(@Nullable List<Integer> integers) {
int firstVal = integers.get(0);
Log.d(TAG, "onChanged val " + firstVal);
tv.setText("" + firstVal);
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// first val in List is incremented but onChanged isn't called, why?
int newVal = vals.getValue().get(0) + 1;
vals.getValue().set(0, newVal);
Log.d(TAG, "set val at index 0 to " + newVal);
}
});