Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hilt Inject into ViewModel without constructor params

With the new dependency injection library Hilt, how to inject some classes into ViewModel without constructor params and ViewModelFactory? Is it possible?

Like in Fragment, we use only @AndroidEntryPoint and @Inject.

like image 235
Pavel Poley Avatar asked Jul 25 '26 05:07

Pavel Poley


1 Answers

how to inject some classes into ViewModel without constructor params and ViewModelFactory? Is it possible?

Hilt supports constructor injection of ViewModel via the @HiltViewModel (previously @ViewModelInject) annotation.

This allows for any @AndroidEntryPoint-annotated class to redefine their defaultViewModelProviderFactory to be the HiltViewModelFactory, which allows the creation of @HiltViewModel-annotated ViewModels correctly instantiated via Dagger/Hilt.

NEW HILT VERSION:

@HiltViewModel
class RegistrationViewModel @Inject constructor(
    private val someDependency: SomeDependency,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    ...
}

OLD HILT VERSION:

class RegistrationViewModel @ViewModelInject constructor(
    private val someDependency: SomeDependency,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    ...
}

And then

@AndroidEntryPoint
class ProfileFragment: Fragment(R.layout.profile_fragment) {
    private val viewModel by viewModels<RegistrationViewModel>() // <-- uses defaultViewModelProviderFactory
like image 122
EpicPandaForce Avatar answered Jul 28 '26 13:07

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!