I’m following Kotlin tutorial on learning Dagger Hilt for dependency injection. The tutorial uses
class MainActivity: AppCompatActivity() {
private val viewModel: TestViewModel by viewModels()
}
in the MainActivity to inject the viewmodel.
It requires a dependency: implementation "androidx.activity.activity-ktx:1.1.0" to do so.
I’m trying to learn hilt in Java so I’m unsure what the Java equivalent of injecting the viewmodel into my activity is.
This is incorrect and doesn’t work
@Inject
private TestViewModel testViewModel;
and using
testViewModel = new ViewModelProvider(this).get(TestViewModel.class);
doesn’t seem like dependency injection.
What is the equivalent of by viewModels() in Java?
>Solution :
testViewModel = new ViewModelProvider(this).get(TestViewModel.class) is indeed exactly what by viewModels() does for you.
You’ll note that both by viewModels() and new ViewModelProvder(this) don’t pass in a custom ViewModelProvider.Factory instance – that’s because they use the default Factory – the one setup by Hilt to correctly create your ViewModel via DI.