LiveData update on object field change

后端 未结 5 1697
渐次进展
渐次进展 2020-11-27 12:49

I\'m using Android MVVM architecture with LiveData. I have an object like this

public class User {
    private String firstName;
    private String lastName;         


        
5条回答
  •  忘掉有多难
    2020-11-27 12:57

    I don't think there is any best practice as such recommended by android for this. I would suggest you to use the approach which uses cleaner & less boilerplate code.

    If you are using android data binding along with LiveData you can go with the following approach:

    Your POJO object would look something like this

    public class User extends BaseObservable {
        private String firstName;
        private String lastName;
    
        @Bindable
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
            notifyPropertyChanged(BR.firstName);
        }
    
        @Bindable
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
            notifyPropertyChanged(BR.lastName);
        }
    }
    

    So you would be already having a class which notifies whenever its property changes. So you can just make use of this property change callback in your MutableLiveData to notify its observer. You can create a custom MutableLiveData for this

    public class CustomMutableLiveData
            extends MutableLiveData {
    
    
        @Override
        public void setValue(T value) {
            super.setValue(value);
    
            //listen to property changes
            value.addOnPropertyChangedCallback(callback);
        }
    
        Observable.OnPropertyChangedCallback callback = new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
    
                //Trigger LiveData observer on change of any property in object
                setValue(getValue());
    
            }
        };
    
    
    }
    

    Then all you need to do is use this CustomMutableLiveData instead of MutableLiveData in your View Model

    public class InfoViewModel extends AndroidViewModel {
    
        CustomMutableLiveData user = new CustomMutableLiveData<>();
    -----
    -----
    

    So by doing this you can notify both view & LiveData observer with little change to existing code. Hope it helps

提交回复
热议问题