I recently started using DI in my project through Dagger Hilt. I'm having no problems when injecting instances into Activities, fragments... etc. But I am not sure how to inject a class instance into ViewModel.
My approach at the moment consists of adding the classes I need to the constructor of the viewmodel as such:
class MainViewModel @ViewModelInject constructor(
application: Application,
@Named("classA") var classA: ClassA,
@Named("classB") var classB: ClassB
) : AndroidViewModel(application)
and then in my AppModule:
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
@Named("ClassA")
fun provideClassA(@ApplicationContext context: Context) = ClassA(context)
@Singleton
@Provides
@Named("ClassB")
fun provideClassB(@ApplicationContext context: Context) = ClassB(context)
}
Which works great, but ideally and in the case I wanted to add many more instances of other classes, I would prefer doing
@Inject
lateinit var classA:ClassA
But I presume this is not possible, as adding @AndroidEntryPoint to the viewModel is not possible, so how are classes injected into viewmodel? or do we just add them to constructor, as in my current solution?