How to access context in repository [MVVM]
I ended up injecting the context via dagger. However, from my point of view making your ViewModel
extend from AndroidViewModel
is also an valid option and definitely the easier one. If I were developing an simple and small application I would probably recommend just extending from AndroidViewModel
to avoid unnecessary boilerplate code from dagger.
I followed the dagger series from codingwithmith in order to implement my own solution. So his channel might be useful for future readers: https://www.youtube.com/channel/UCoNZZLhPuuRteu02rh7bzsw/featured
Using Android Hilt
//Dagger - Hilt
def hilt_version = "2.31.2-alpha"
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
def hilt_viewmodel_version = "1.0.0-alpha03"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_viewmodel_version"
kapt "androidx.hilt:hilt-compiler:$hilt_viewmodel_version"
.
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@Provides
fun provideContext(application: Application): Context = application.applicationContext
}
Then pass it via constructor
class MyRepository @Inject constructor(private val context: Context) {
...
}