Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Live Data observe for object single property change

In Android project implemented Android Architecture component successfully as per developer guideline but the problem is we can observe full object change using LiveData

  mQueViewModel.getLiveQuestion().observe(this, new Observer<Question>() {
        @Override
        public void onChanged(@Nullable Question question) {
            Log.i(TAG, "onChanged: ");
            setQuestionDetails();
        }
    });

Any single object property change fire OnChanged this cause to set all data again to UI So is there any way to implement property change like onDescriptionChange, onImageChange ...

like image 875
Rajesh dhalange Avatar asked Dec 13 '25 23:12

Rajesh dhalange


1 Answers

To do that you could use the ViewModel to break the data in smaller pieces. Something like this should work:

private LiveData<Question> questions;
private MediatorLiveData<String> description;

public MQueViewModel() {

    description = new MediatorLiveData<>();
    description.addSource(questions, new Observer<Question>() {
        @Override
        public void onChanged(@Nullable Question question) {
            if (question == null) return;
            if (!question.description.equals(description.getValue())) {
                description.setValue(question.description);
            }
        }
    });

}

and have than have your UI subscribe to description. Add similar MediatorLiveData to any other property change u need.

like image 174
Budius Avatar answered Dec 16 '25 21:12

Budius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!