问题描述
我正在尝试在我的 android 应用程序中实现 MVVM 模式.我已经读过 ViewModels 不应该包含特定于 android 的代码(为了使测试更容易),但是我需要为各种事情使用上下文(从 xml 获取资源、初始化首选项等).做这个的最好方式是什么?我看到 AndroidViewModel
有对应用程序上下文的引用,但是它包含特定于 android 的代码,所以我不确定它是否应该在 ViewModel 中.这些也与 Activity 生命周期事件有关,但我使用 dagger 来管理组件的范围,所以我不确定这会如何影响它.我是 MVVM 模式和 Dagger 的新手,因此非常感谢您的帮助!
I am trying to implement MVVM pattern in my android app. I have read that ViewModels should contain no android specific code (to make testing easier), however I need to use context for various things (getting resources from xml, initializing preferences, etc). What is the best way to do this? I saw that AndroidViewModel
has a reference to the application context, however that contains android specific code so I'm not sure if that should be in the ViewModel. Also those tie into the Activity lifecycle events, but I am using dagger to manage the scope of components so I'm not sure how that would affect it. I am new to the MVVM pattern and Dagger so any help is appreciated!
推荐答案
我最终做了什么,而不是直接在 ViewModel 中拥有一个 Context,我创建了提供程序类,例如 ResourceProvider,它可以为我提供我需要的资源,并且我将这些提供程序类注入到我的 ViewModel 中
What I ended up doing instead of having a Context directly in the ViewModel, I made provider classes such as ResourceProvider that would give me the resources I need, and I had those provider classes injected into my ViewModel
这篇关于如何在 Android MVVM ViewModel 中获取上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!