sgtpotatoe
sgtpotatoe

Reputation: 430

Dagger Hilt how to inject classes into ViewModel

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?

Upvotes: 2

Views: 2960

Answers (1)

Andrew
Andrew

Reputation: 4742

You just add them to the constructor. And in your case, you don't even need @Named() because both of you dependencies provide another class. So:

class YourViewModel @ViewModelInject(
   @ApplicationContext private val context: Context
   private val classA: ClassA, // or non-private, but it has to be a val
   private val classB: ClassB // or non-private, but it has to be a val
) : ViewModel()

Furthermore, you don't need to use AndroidViewModel here. Dagger will provide you the application context via @ApplicationContext private val context: Context. Be aware that in order to use this viewmodel, the fragment and activity has to be annotated with @AndroidEntryPoint

Upvotes: 2

Related Questions