[英]Dagger inject Context in a ModelView
我试图在我的ModelView中注入Context
,但是我有点困惑:
这是我的Module
,我向他发送了一个Application
以供以后使用此上下文,但是我不知道它来自此Application
或如何使用:
@Module
class module {
@Provides @Singleton fun appContext(application: Application): Context{
return application
}
}
这是我的Component
:
@Component(modules = [module::class])
interface component {
fun providesApplication(): Application
}
最后,我不知道如何在我的ViewModel中注入它,因为它没有构造函数来注入它。
我应该如何将上下文注入到ViewModel
?
已经有带上下文的内置ViewModel
,用AndroidViewModel
替换了从ViewModel
继承的内容
参见: https : //developer.android.com/reference/android/arch/lifecycle/AndroidViewModel
或者,您可以尝试这样的事情:
class YourViewModel @Inject constructor(context:Context) : ViewModel()
只是一个建议,如果没有其他效果,请听我说...
var context: Context? = null
fun initViewModelWithContext(context: Context) {
this.context = context
}
如果找不到带匕首的解决方案,您也可能会做类似的事情。 然后,您所有的函数都可以使用此上下文的本地实例,并且此ViewModel
将在需要时被破坏/创建,因此不会引起任何内存问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.