Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ViewModel's coroutine scope with Hilt

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.

like image 550
Ov3r1oad Avatar asked Mar 21 '26 04:03

Ov3r1oad


1 Answers

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.

like image 95
MrMikimn Avatar answered Mar 22 '26 17:03

MrMikimn