javaandroidkotlindaggermodel-view

Dagger inject Context in a ModelView


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?


Solution

  • There is already build-in ViewModel with context, replace inheritance from ViewModel with AndroidViewModel

    See: https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel