3

I tried to inject viewModel to my base activity using hilt

abstract class BaseActivity<VB: ViewBinding, VM: BaseViewModel>(val bindingFactory(LayoutInflater) -> VB) : AppCompatActivity() {

    private val viewModel: VM by viewModels<>()
    lateinit var binding: VB
}

but am getting error here on viewModels() function as "Property delegate must have a 'getValue(BaseActivity , KProperty*>)' method. None of the following functions are suitable."

how do I inject viewModel in base classes using hilt, or is it possible to use base classes with hilt?

Progman
  • 16,827
  • 6
  • 33
  • 48
Milan Jayan
  • 96
  • 1
  • 6
  • Why don't you use the bindings and viewmodels in the activity as is as if without Hilt? One of the main thrusts of Hilt is to use Android's built-in instance creation as the seams for injection into things like viewmodels – possum Nov 11 '21 at 12:04
  • Since am having multiple activities and fragments I intend to use base classes to reduce redundancy, was using this architecture before with dagger. This is my first build using hilt so am unaware of the limitations. – Milan Jayan Nov 11 '21 at 12:14
  • I'm asking the same question but with Dagger android. Does someone know? – Oscar Ivan Feb 03 '22 at 20:23

1 Answers1

2

I hope this is not too late but I was able to inject viewModel into base fragment this way:

class BaseFragment<T : ViewDataBinding, V: ViewModel>(private val modelClass: Class<V>) : Fragment() {
@Inject
protected lateinit var viewModel: V
}

and the usage would be like:

@AndroidEntryPoint
ScanFragment:BaseFragment<FragmentScanBinding, ScanViewModel>(ScanViewModel::class.java){