如何在Android MVVM ViewModel中获取上下文 [英] How to get Context in Android MVVM ViewModel

查看:1692
本文介绍了如何在Android MVVM ViewModel中获取上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的android应用中实现MVVM模式.我已经读过ViewModels应该不包含任何android特定代码(以使测试更容易),但是我需要对各种事物使用上下文(从xml获取资源,初始化首选项等).做这个的最好方式是什么?我看到AndroidViewModel具有对应用程序上下文的引用,但是其中包含android特定的代码,因此我不确定是否应该在ViewModel中使用它.那些也与Activity生命周期事件相关联,但是我使用匕首来管理组件的范围,所以我不确定这将如何影响它.我是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中获取上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆