Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hilt – what is the Java equivalent to kotlin's "by viewmodels()" to inject viewmodel into activity?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading