One approach to solving this is using Android's LiveData.
In your situation, since you'd like to observe an int
, you can do something like this:
public MutableLiveData<Integer> mCurrentIndex = new MutableLiveData<>();
To change your value, you would do this:
mCurrentIndex.setValue(12345); // Replace 12345 with your int value.
To observe the changes you would do the following:
mCurrentIndex.observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable final Integer newIntValue) {
// Update the UI, in this case, a TextView.
mNameTextView.setText("My new current index is: " + newIntValue);
}
};);
}
This approach is useful because you can define a ViewModel to segregate your logic from your Activity while having the UI observe and reflect the changes that occur.
By separating your logic out to the ViewModel, your logic becomes more easily testable since writing tests for your ViewModel is relatively easier than writing tests for your Activity.
For more information on LiveData check out this link.