Suppose, I have ViewModel class with some UseCase in its constructor. This UseCase, on the other hand, has a CoroutineScope in its constructor. And I want to use the viewModelScope as an argument. Can I do it with Hilt?
@InstallIn(ViewModelComponent::class)
abstract class ViewModelModule {
@Provides
fun provideUseCase(scope: CoroutineScope) = MyUseCase(scope)
}
...
@HiltViewModel
class MyViewMode(useCase: MyUseCase): ViewModel() {
...
}
As far as I understand, ViewModelComponent only has SavedStateHandle as a default binding, not even ViewModel itself.
If your UseCase depends on the scope of the ViewModel that consequently depends on the UseCase, you have a dependency loop and you can't resolve it using Hilt.
You'd be better off passing down a provider for the UseCase, and initializing it inside the ViewModel, or better yet, not depend on the CoroutineScope and instead make your UseCase interface suspend
You can use KTX extensions for lifecycle-aware components, and use the viewModelScope extension. See here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With