0

In my case, I have a BaseViewModel which all viewModels inherit from this class. I want to add a base repo to the base view model by field injection. Injecting by constructor does not work in my case because I have to provide that repo to all viewModels inherited from baseViewModel too. I am doing like this:

open class BaseVM @Inject constructor() : ViewModel() {

    @Inject
    lateinit var sampleRepo: SampleRepo

    fun test(): String {
        return sampleRepo.test()
    }

}

but I get this error

lateinit property sampleRepo has not been initialized

this is my module:

@Module
@InstallIn(SingletonComponent::class)
interface SampleModule {

    @Binds
    fun bindSampleRepo(repoImpl: SampleRepoImpl): SampleRepo

 }
Reza Faraji
  • 435
  • 1
  • 7
  • 14
  • Have you annotated your BaseVM with @HiltViewModel ? And why not injecting the repo in the constructor? – Hamed Nov 26 '22 at 08:53
  • 2
    @Hamed If I inject it in constructor then I have to inject base repo to all viewModels that have inherited from BaseVM, and there are just some VMs that need to use the base repo. And for the HiltViewModel annotation part, I don't need to inject BaseVM directly to Composable – Reza Faraji Nov 26 '22 at 10:19
  • Does this answer your question? [Field Injection via Hilt outside of Fragment and Activity](https://stackoverflow.com/questions/65813581/field-injection-via-hilt-outside-of-fragment-and-activity) – Mark Nov 26 '22 at 10:51

0 Answers0