Injecting dependencies in ViewModel with inheritan...
# android
s
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:
Copy code
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`:
Copy code
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?
not kotlin but kotlin colored 2
🧵 1
r
I would strongly advise against having such types of base classes. You can reuse functionalities via delegation or other patterns.
🙌 3
💯 1
c
Image from iOS.jpg
w
Given the current state of the code you presented, you need to drop hilt/dagger related annotations from BaseViewModel, make it abstract and duplicate the dependencies needed for that class in every one of it's children constructors, keeping in mind that they are the ones that need the hilt/dagger annotations. Now that being said, I second strongly what @Rok Oblak said. Using inheritance to leverage code sharing is a bad practice, (almost) always prefer composition over it. Lastly, as @Chrimaeon correctly suggested, this channel is dedicated to Kotlin related topics only, in the context of android. Maybe would it be advised in your case to use another platform, such as stackoverflow.
s
thank you for your response, it was very helpful.
🙌 1
p
Stop creating base classes for "anything" in your code,
242 Views