Injecting dependencies in ViewModel with inheritance using Hilt without constructor parameters
Hello, I need some advice on a problem I'm facing. I have a feature A with sub-features AA and AB. I want to separate the logic of AA and AB by creating a
BaseViewModel
and then have
AAViewModel
and
ABViewModel
inherit from it. We are using Hilt in our project to inject dependencies into the
BaseViewModel
.
Here is an example of what I am trying to achieve:
kotlin
@HiltViewModel
open class BaseViewModel @Inject constructor(
private val sampleUseCase: SampleUseCase,
private val anotherUseCase: AnotherUseCase
) : ViewModel() {
// BaseViewModel logic
}
The problem arises when I try to implement the class that inherits from `BaseViewModel`:
kotlin
@HiltViewModel
class AAViewModel @Inject constructor(
private val secondSampleUseCase: SecondSampleUseCase
) : BaseViewModel(
// error! Too many parameters to pass
) {
// AAViewModel logic
}
When inheriting from
BaseViewModel
, I need to pass many member variables through the constructor, which is cumbersome and error-prone. I want to eliminate the constructor parameters. How can I achieve this using Hilt?