LiveData update on object field change

后端 未结 5 1688
渐次进展
渐次进展 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 13:11

    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:

    
        
    
    
    ...
    
    
    

提交回复
热议问题