I\'m using Android MVVM architecture with LiveData. I have an object like this
public class User {
private String firstName;
private String lastName;
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 in the ViewModel
ViewModel
class SampleViewModel : ViewModel() {
val user = MutableLiveData()
fun onChange() {
user.value.firstname = "New name"
user.value = user.value // force postValue to notify Observers
// can also use user.postValue()
}
}
Activity/Fragment file:
viewModel = ViewModelProviders
.of(this)
.get(SampleViewModel::class.java)
// when viewModel.user changes, this observer get notified and re-bind
// the user model with the layout.
viewModel.user.observe(this, Observer {
binding.user = it //<- re-binding user
})
Your layout file shouldn't change:
...