简体   繁体   English

如何在我所有的视图模型中共享同一个数据实例 class?

[英]How to share the same instance of a data class across all my view models?

I'm very new to android development and struggling to find this answer.我是 android 开发的新手,正在努力寻找这个答案。 Is it possible to share the same instance of a data class across all my view models?是否可以在我的所有视图模型中共享数据 class 的相同实例?

Currently when my app first starts, I'm fetching my user's app preferences from a Firestore DB and instantiating a data class instance I have defined to hold all user preferences.目前,当我的应用程序首次启动时,我正在从 Firestore 数据库中获取用户的应用程序首选项,并实例化我定义的用于保存所有用户首选项的数据 class 实例。 I want to have all my view models to have access to the user preferences without every view model having to make the Firestore DB call and creating its own data class instance.我想让我所有的视图模型都可以访问用户首选项,而无需每个视图 model 都必须调用 Firestore 数据库并创建自己的数据 class 实例。 Is it possible to share the same instance of a data class between all of my view models?是否可以在我的所有视图模型之间共享数据 class 的相同实例?

I could use dagger hilt to to fetch the preferences from Firestore, create my data class instance, and provide that as a dependency of injection....but if a user updates their preferences after loading the app then those updates won't reflect in the data class instance that is injected via dagger hilt, correct?我可以使用匕首柄从 Firestore 获取首选项,创建我的数据 class 实例,并将其作为注入的依赖项提供....但是如果用户在加载应用程序后更新他们的首选项,那么这些更新将不会反映在通过匕首柄注入的数据 class 实例,对吗?

Admittedly I might be going about this the wrong way.不可否认,我可能会以错误的方式解决这个问题。 I'm ultimately trying to understand what the best way to share my app preferences that are stored in an external DB to all of my view models.我最终试图了解将存储在外部数据库中的应用程序首选项共享到我所有视图模型的最佳方式。

After getting the data in your viewModel, initialize the related viewmodel in your fragment as activityViewModel as below;在您的viewModel中获取数据后,将您的片段中的相关viewmodel初始化为activityViewModel,如下所示;

val shareViewModel by activityViewModels<ShareViewModel>()

If you use it in your activity just set this for owner parameter as below;如果您在活动中使用它,只需将其设置为所有者参数,如下所示;

val shareViewModel = ViewModelProvider(this)[ShareViewModel::class.java]

It provides you sharing data across your app它使您可以在整个应用程序中共享数据

Moreover, check this codelab https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel此外,检查此代码实验室https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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