I'm trying to inject the Context
in my ModelView but I'm a little bit confused:
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
class module {
@Provides @Singleton fun appContext(application: Application): Context{
return application
}
}
And here is my 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.
How should I inject the context to my ViewModel
?
There is already build-in ViewModel
with context, replace inheritance from ViewModel
with AndroidViewModel
See: 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.