I'm using Android MVVM architecture with LiveData. I have an object like this
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And my view model looks like this
public class InfoViewModel extends AndroidViewModel {
MutableLiveData<User> user = new MutableLiveData<>();
public InfoViewModel(@NonNull Application application) {
super(application);
User user = new User();
user.setFirstName("Alireza");
user.setLastName("Ahmadi");
this.user.setValue(user);
}
public LiveData<User> getUser(){
return user;
}
public void change(){
user.getValue().setFirstName(user.getValue().getFirstName() + " A ");
}
}
How can I make sure when some filed in user object changes observers get notified? BTW it is important to me to keep this data in the separate object and not use primary values like Strings in my ViewModel.
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
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
Then all you need to do is use this CustomMutableLiveData instead of MutableLiveData in your View Model
So by doing this you can notify both view & LiveData observer with little change to existing code. Hope it helps
When using MVVM and LiveData, you can re-bind the object to the layout so it will trigger all changes on the UI.
Given "user" is a
MutableLiveData<User>
in the ViewModelViewModel
Activity/Fragment file:
Your layout file shouldn't change:
If you are using Kotlin and LiveData, I can offer you 2 ways - with and without extension fucntion:
Without extension function
Same, but with extension
For your observer get notified you should use
setValue
if you do thisuser.getValue().setFirstName(user.getValue().getFirstName() + " A ");
your observer will not be notified !View Model
Activity / Fragment
Somewhere in your activity / fragment
This will trigger the observer :
If you want to update only one field from an object instead of update the whole object you should have multiples
MutableLiveData<String>