Provide Dependencies To Hilt | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/11277584-dependency-injection-with-hilt-fundamentals/lessons/3

I was using hilt and. its great but I got couple questions about the scopes and the modules, because of for example I dont know why cant I provide my useCases in me ViewModule were I provide, mi VM, hilt only let me do. that in any module similar to application, but really I dont need the object for all the application.

The other. thing is that in the viewModel

@ActivityScoped // when I need it, because its a. fragment VM, and if I dont use it, it works fine.
@ActivityScoped
class MainViewModel @ViewModelInject constructor(
private val getCountersUC: GetCountersUseCase) {
}

@Inject constructor. // where , when must. I use it ??

and what about the use of @Binds , for example all my clases has an interface to make it test able. But I didnt knew how to use @Bind, the I let

@Provides
    fun provideIncreaseCounterUseCase(repository: CounterRepository): IncreaseCounterUseCase =
        IncreaseCounterUseCaseImp(repository)

Finally, how can. we create unittest for it?

Hey @aliceresponde!

Not entirely sure I understand your problem, but basically, you need to have the same Scope in your classes/providers, as you do in your modules.

You cannot mix scopes, so if you want to have an ActivityScope ViewModel, in a module that uses @Singleton or your custom ApplicationScope, then that wonโ€™t work.

Regarding the @Inject constructor question, you should/can use it to easily provide a dependency, using the constructor of the class. Then Hilt/Dagger will read the parameters in constructor, and check if they exist, and if so, it will be provided.

You should use this with the @Bind annotation, for quick & easy providers.

To use binds, youโ€™d do something like:

@Binds
abstract fun provideIncreaseCounterUseCase(repository: IncreaseCounterUseCaseImpl): IncreaseCounterUseCase

Itโ€™s shown in the video, and explained that the binds takes the parameter of the concrete dependency you provided using @Inject or otherwise, and then returns the abstract interface type in your return type definition.

Hopefully that makes sense.

Regarding testing, what do you want to test? Hilt? Business logic? Integration between dependencies?