2

I am experiencing the new architectural components from google namely LiveData and ViewModel. By combining both APIs we can have the view model listening and updating the data in a reactive way.

My question is how data should be represented in a ViewModel more specifically, which way is better between having data exploded as separate fields as the following

class UserViewMode : ViewModel() {
    var name = MutableLiveData<String>
    vat lastName = MutableLiveData<String>
}

Or by encapsulating the data in a data holder/model class which contains both name and last name and having the view model observing this model class in a LiveData observer as the following

class UserViewMode : ViewModel() {
    var user = MutableLiveData<User>
}

Thanks in advance.

AouledIssa
  • 2,528
  • 2
  • 22
  • 39

2 Answers2

2

Second approach is better.

class UserViewModel : ViewModel() {
    var user = MutableLiveData<User>
}

Because encapsulating data inside a model (User) object is better than keeping all the data separate. Main advantages I can see are 1. Clean code and architecture. 2. Model object can be used/passed between other components like GSON (to parse data into model object), Room database.

If there are multiple User objects and they need to be presented in a RecyclerView then you have to encapsulate the data into one object. Otherwise the code becomes a mess with multiple lists.

AJAY PRAKASH
  • 1,110
  • 7
  • 8
  • It's pretty much what i thought, but having that approach, the live data is only observing the User object for any change but not its fields. I have implemented that but with every change i commit into any field of the User Object i will have to rest the live data value like `user.value = user.value` to force the view to rebind to the new data. Is there any other way to have live data listen also to `User` fields? – AouledIssa Nov 24 '18 at 12:26
  • This might help you. It uses Data binding https://stackoverflow.com/questions/48020377/livedata-update-on-object-field-change – AJAY PRAKASH Nov 24 '18 at 13:23
  • I am already using the second answer https://stackoverflow.com/a/52287357/2057782 but how would it affect the performance? – AouledIssa Nov 24 '18 at 13:26
  • I don't think there are any performance issues as they are just callbacks using Observable and Observer pattern. – AJAY PRAKASH Nov 24 '18 at 14:25
2

I think it depends only on how you get the data and you should think of are the fields changing separately or not?

For ex, if you are getting it like:

  • User, than there is no need to separate it into fields
  • On the other hand if you are changing the name separately from lastName you should have two fields for that.

Do it how it makes sense.

Róbert Nagy
  • 6,720
  • 26
  • 45
  • Yes that makes sense to me! Because if u have your data model encapsulating data and your data is changing separately you will have to reset the value of the data model per field change – AouledIssa Dec 02 '18 at 10:45