LiveData update on object field change

后端 未结 5 1699
渐次进展
渐次进展 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条回答
  •  猫巷女王i
    2020-11-27 13:16

    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.

    You can use androidx.lifecyle.Transformation class to monitor for individual fields.

    val user = MutableLiveData();
    //to monitor for User.Name
    val firstName: LiveData  = Transformations.map {it.firstName}
    val lastName: LiveData  = Transformations.map {it.lastName}
    

    you update user as per normal, and listen for firstname/lastname to monitor for changes in those fields.

提交回复
热议问题