[英]MVVM: Complex View/ViewModel -> Multiple LiveData objects?
Most of the MVVM examples are dealing with very simple user interfaces. 大多数MVVM示例都处理非常简单的用户界面。
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. 正如我在其他地方读到的那样,多个ViewModel对象是一种错误的模式。
So, as I see it there are two solutions for that: 因此,正如我所见,有两种解决方案:
Create a single object (and single LiveData for it), that wraps all other data objects. 创建一个包装所有其他数据对象的单个对象(以及单个LiveData)。
But there's a problem with this - each data object that gets updated will cause the whole UI to update. 但这有一个问题-每个要更新的数据对象都会导致整个UI进行更新。
Create multiple objects (and multiple LiveData objects for it). 创建多个对象(以及多个LiveData对象)。
It means that I need to observe each LiveData object. 这意味着我需要观察每个LiveData对象。 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 您提到的第一点:是的,这不是最佳的模式,但是如果数据量较小,则分离LiveDatas会增加工作量,但收益却减少
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. 您提到的第二点:是的,这是最佳选择,您可以为要更新的每个View都拥有一个LiveData对象,并从活动或片段中观察它们。 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. 关于Mutilple ViewModels:如果一个ViewModel中发生的事情太多(LiveData对象或函数),则在同一活动/片段中使用多个ViewModels模式也是一种选择。 This is only recommended to make viewModels lighter. 仅建议这样做以使viewModels更轻。 So only use this if you are having a large viewModel class 因此,仅当您拥有大型viewModel类时才使用此方法
ViewModel
s for discrete types of information. 创建ViewModel
以获取离散类型的信息。 You could for example have a UserViewModel
that deals with all state regarding a User
. 例如,您可以拥有一个UserViewModel
来处理有关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
). 这意味着您可以在另一个上下文中使用相同的ViewModel
,而无需提取不必要的数据(就像您只有一个God ViewModel
)。
LiveData
objects as you need to model your view. 根据需要创建尽可能多的LiveData
对象以对视图进行建模。 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. 如果您有一个User
,则应将其用于LiveData
而LiveData
为电子邮件地址,显示名称,年龄等使用LiveData
。这将使数据绑定的过程变得简单得多。 Try to keep things logically grouped together. 尝试将所有内容按逻辑分组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.