简体   繁体   中英

MVVM: Complex View/ViewModel -> Multiple LiveData objects?

Most of the MVVM examples are dealing with very simple user interfaces.

But lets say I have an activity with many views to update (ie lots of data)

As I read in other places, multiple ViewModel objects is a bad pattern.

So, as I see it there are two solutions for that:

  1. Create a single object (and single LiveData for it), that wraps all other data objects.
    But there's a problem with this - each data object that gets updated will cause the whole UI to update.

  2. Create multiple objects (and multiple LiveData objects for it).
    It means that I need to observe each LiveData object. Is there a problem with this pattern?

Thanks in Advance!

First Point you mentioned : Yes this is not optimal Pattern to do but if you have small data then, separating LiveDatas is more work for less gains

Second Point you mentioned : Yes this is more optimal, you can have a LiveData object for each View you want to update and observe them all from your activity or fragment. There are no issues in this Pattern.

About Mutilple ViewModels : Multiple ViewModels Pattern in same Activty/Fragment is also an option if you have too many things(LiveData objects or funcitions) happening in one ViewModel. This is only recommended to make viewModels lighter. So only use this if you are having a large viewModel class

  1. Create ViewModel s for discrete types of information.

You could for example have a UserViewModel that deals with all state regarding a User . This means you can use the same ViewModel in another context, without pulling data that might not be necessary (as you would if you had a single God ViewModel ).

  1. Create as many LiveData objects as you need to model your view.

It is better to condense the data into logical objects, where possible. If only to keep things manageable.

If you have a User , you should use that for your LiveData instead of having a LiveData for E-mail address, Display name, Age, etc. That will make things much simpler for your data bindings. Try to keep things logically grouped together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM