Live Data observe for object single property change

2.4k views Asked by At

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 ...

2

There are 2 answers

3
Budius On

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.

0
Alireza On

may be its so late but you can have two option


1- implementing Property “Aware” MutableLiveData as described here

2- whenever the property changed set the value to itself

 private  var _currentPacket = MutableLiveData<PacketEntity>()
 fun test() {
     _currentPacket.value!!.someproperty= somevalue 
     _currentPacket.value=_currentPacket.value 
  }