视图模型工厂和LiveData是什么?有人能用简单的话来解释一下吗?

huangapple go评论87阅读模式
英文:

What is view model factory and livedata. Can anyone explain this in simple words?

问题

以下是要翻译的内容:

  1. 什么是视图模型
  2. 什么是视图模型工厂
  3. 什么是存储库
  4. 什么是LiveData
英文:

I want the explanation of this topic as I am unable to understand from the official document that why and how to use this?

Simple Explanation of these two topics

  1. What is view Model
  2. what is view model factory
  3. what is repository
  4. what is livedata

答案1

得分: 1

  1. ViewModel - ViewModel是一个能够在配置更改时保留的类。例如,你在片段中有一个游戏。最初,分数为零,随着游戏的进行会增加。假设由于某种原因你旋转了设备,分数将丢失,因为在旋转后片段会被重新创建,你的分数将重新初始化为零。这是因为你将分数变量存储在片段中。如果将其存储在ViewModel中,它将在设备旋转时保留下来。因此,你应该将所有的数据都放在ViewModel中,片段应该只在从ViewModel获取数据后显示数据或将输入传递给ViewModel。由于现在所有的数据都在ViewModel中,你还应该只在ViewModel中对数据进行任何处理。比如,何时显示哪些数据,例如分数如何增加。

  2. ViewModelProvider - 那么,如果我们在片段中初始化ViewModel,该如何创建ViewModel呢?因为在配置更改时片段将被重新创建,因此ViewModel也将被重新创建,所以在片段中初始化它没有意义。因此,我们不创建视图模型,而是要求提供者为我们提供视图模型,提供者为我们创建视图模型。当我们第一次请求时,它为我们创建一个新的ViewModel,但是每次之后,即使我们的片段被重新创建,它也会返回先前创建的ViewModel,因此不会再次创建它。

  3. ViewModelFactory - 现在,考虑一种情况,我们需要在ViewModel初始化期间传递一些数据,即我们必须调用构造函数。例如,我们想要传递默认分数,比如100。我们不能在片段中调用构造函数,因为每次重新创建片段时,分数都将被重新初始化。所以,我们使用一个工厂。基本上,工厂根据我们的需求为我们创建视图模型,而提供者为我们提供视图模型。我们告诉工厂如何创建ViewModel并传递数据给工厂,工厂创建ViewModel。提供者与工厂一起工作,如上所述提供ViewModel。如果提供者已经创建了一个ViewModel,它会将它提供给我们,工厂不会创建一个新的ViewModel。

  4. LiveData - 现在,ViewModel拥有了所有的数据,我们只在ViewModel中执行所有的逻辑。假设你的分数发生了变化,我们如何更新UI中的数据?我们可能在ViewModel中有对片段的引用,然后更新相应的视图。然而,绝对不应该这样做。ViewModels不应该引用activity或fragment。但是,为什么呢?因为如果你引用一个片段,当设备旋转时片段被销毁,你持有的是一个不存在的引用,这可能会导致错误。那么如何更新UI呢?我们使用另一个称为LiveData的类。LiveData是可观察的类。这意味着你可以观察LiveData的变化。LiveData在ViewModel类中保存实际数据,所以基本上在ViewModel中的所有数据变量都会被LiveData包装。所以,我们的分数变成了 LiveData<Int> score。现在,在片段中我们观察这个LiveData,每当分数变化时,我们在片段中就会知道,并且可以轻松地更新数据。

  5. Repository - 以上讨论的内容都是生命周期库提供的实际类。但是,仓库是MVVM设计模式中使用的一个概念类。假设现在你将游戏制作成了在线游戏,因此分数在本地数据库和远程服务器上都有维护。那么,当你向ViewModel请求分数时,它会搜索本地数据库和远程服务器。我们在哪里编写此代码?它被编写在一个我们称之为仓库的单独类中,因为它具有从所有来源访问数据的API。你也可以在ViewModel类中执行所有这些逻辑,但是为了更好的代码,我们将它放在一个单独的类中。

这些是关于这些组件的一些基本解释。然而,有很多东西在一个帖子中无法涵盖。所以,我建议你阅读更多详细的文档。仅仅阅读文档并完全理解所有内容可能会很困难,所以尝试实施你所阅读的内容。你可以在CodeLabs上找到教程。

英文:
  1. ViewModel - It is class that can survive configuration changes.
    For example, you have a game in your fragment. Initially, the score is zero and it increases as you play, suppose for some reason you rotate your device, the score will be lost, because after rotation the fragment is re-created and your score is re-initialized to zero. This happens because you are storing your score variable in fragment. If you store it in viewModel, it will survive device rotation. So, you should have all your data in view model, and fragment should only display the data after getting from view model or pass the input to view model. Since all your data is now in ViewModel, you should also do any processing on the data in the view model only. Like, what data to be displayed when, for example how score increases.

  2. ViewModelProvider - So, how do we create ViewModel, if we initialize it in our fragment, it's of no use because on configuration change fragment will be re-created therefore ViewModel will be re-created. Hence we don't create view models, we ask a provider to provide view models, and the provider creates view model for us. When we ask for first time, it creates a new ViewModel for us, but every next time, it returns previously created ViewModel, hence not creating it again, even if our fragment is re-created.

  3. ViewModelFactory - Now, consider a case in which we need to pass some data in ViewModel during initialization, i.e. we have to call constructor. For example, we want to pass some default score of say 100. How do we do that? We cannot call constructor in fragment, because every time we re-create a fragment, score will be re-initialized. So, we use a factory. Basically, factory creates the view models for us according to our needs, and provider provides the ViewModel to us. We tell the factory how to create the ViewModel and pass data to factory and factory creates the viewModel. The provider works with factory to provide viewModel as mentioned above. If a provider already has a viewModel created, it gives us that, and factory doesn't create a new one.

  4. LiveData - Okay, now the viewModel has all data and we do all logic in the viewModel only. Suppose your score changed, how do we update the data in UI? We may have reference of our fragment in viewModel and then update the corresponding view. However, this should NEVER be done. ViewModels should never reference activity or fragment. But, why? Because if you reference a fragment, and the fragment is destroyed when device rotates, you are holding reference to something that doesn't exist, this can lead to bugs.
    So how to update the UI then? We use another class called LiveData. LiveData is observable class. This means you can observe the LiveData for changes. LiveData holds the actual data in the ViewModel class, so basically inside the viewModel all data variables will be wrapped by LiveData. So, our score becomes LiveData&lt;Int&gt; score. Now, in our fragment we observe this LiveData, and whenever the score changes, we know about it in fragment and we can update the data easily.

  5. Repository - Whatever we discussed above were actual classes provided by the LifeCycle library. But, repository is a concept class used in MVVM design pattern. Suppose, now you made the game online, so the score is maintained in local database as well as on remote server. So, when you ask ViewModel for your score, it searches local database and remote server. Where do you write code for this? It is written in a separate class which we call repository, because it has APIs for accessing data from all sources. You can do all this logic inside your ViewModel class as well, but for better code, we put it in separate class.

This is some basic explanation about these components. However, there are lots of things that can't be covered in one post. So, I suggest you going through documentation for more details. Just reading the documentation and understanding everything would be difficult, so try implementing whatever you read. You can follow tutorials on CodeLabs.

答案2

得分: 0

**ViewModel(视图模型)**只是一个生命周期比Android组件(基本上是活动或片段)长的类。因此,在Android中用于管理数据(保存或检索)。这意味着存储在ViewModel中的任何变量(主要是LiveData)在任何配置更改(如设备旋转)后都将保持其值安全。Android组件可以检索此值。

**LiveData(生命周期感知数据)**是一个可观察类,意味着它可以被Android组件类观察到。它们观察LiveData中的任何更改并更新其用户界面。UI上的任何操作都是可以用来更新LiveData的事件。

**Repository(存储库)**是一种模式,充当数据层和UI层之间的接口。它在MVVM架构中经常被使用。数据层包括dao、数据库类等,UI层包括活动、片段或服务等(Android组件)。有时,ViewModel需要一些类似上述存储库类的依赖项。**ViewModelFactory(视图模型工厂)**允许您将这些依赖项分配给ViewModel。

英文:

ViewModel is just a class which has life cycle greater than the android component (basically activity or fragment) . Thus, useful in Android to manage data (save or retrieve). This means any variable ( mostly a Live data) with data stored in viewModel will be have its value safe even after any configuration change ( like device rotation). The Android components can retrieve this value.

Livedata is an observable class meaning it can be observed by the Android component classes. They observe any changes in the livedata and update their UI. Any action on the Ui is an event which can be used to update the livedata.

Repository is a pattern and act as an interface between data layer and Ui Layer. it is mostly used in MVVM architecture. Data layer includes the dao, databases classes etc. and Ui layer includes activities ,fragments or services etc. (Android components). Sometimes, ViewModel needs some classes like above repository class as a dependencies.
The ViewModelFactory lets you assign this dependencies to the viewModel.

huangapple
  • 本文由 发表于 2023年8月9日 14:14:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865028-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定