[英]Dagger inject Context in a ModelView
I'm trying to inject the Context
in my ModelView but I'm a little bit confused: 我试图在我的ModelView中注入
Context
,但是我有点困惑:
Here is my Module
, I send him an Application
for later use the context from this, but I don't know where it comes from this Application
or how to take it: 这是我的
Module
,我向他发送了一个Application
以供以后使用此上下文,但是我不知道它来自此Application
或如何使用:
@Module
class module {
@Provides @Singleton fun appContext(application: Application): Context{
return application
}
}
And here is my Component
: 这是我的
Component
:
@Component(modules = [module::class])
interface component {
fun providesApplication(): Application
}
To finish I don't know how to inject this in my ViewModel because this don't have constructor to inject it. 最后,我不知道如何在我的ViewModel中注入它,因为它没有构造函数来注入它。
How should I inject the context to my ViewModel
? 我应该如何将上下文注入到
ViewModel
?
There is already build-in ViewModel
with context, replace inheritance from ViewModel
with AndroidViewModel
已经有带上下文的内置
ViewModel
,用AndroidViewModel
替换了从ViewModel
继承的内容
See: https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel 参见: https : //developer.android.com/reference/android/arch/lifecycle/AndroidViewModel
alternatively, you could try something like this : 或者,您可以尝试这样的事情:
class YourViewModel @Inject constructor(context:Context) : ViewModel()
Merely a suggestion if nothing else works, hear me out... 只是一个建议,如果没有其他效果,请听我说...
var context: Context? = null
fun initViewModelWithContext(context: Context) {
this.context = context
}
you could potentially do something like this as well, if you don't find a solution with dagger. 如果找不到带匕首的解决方案,您也可能会做类似的事情。 all your functions can then use this local instance of context, and this
ViewModel
will be destroyed/created as it is needed so it won't be causing any memory issues 然后,您所有的函数都可以使用此上下文的本地实例,并且此
ViewModel
将在需要时被破坏/创建,因此不会引起任何内存问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.