Dagger: Hilt - injecting viewmodel via navGraphViewModels

Created on 18 Jun 2020  路  1Comment  路  Source: google/dagger

Hello,

I had an issue with the following construct inside an AndroidEntryPoint annotated fragment:

private val scanViewModel: ScanViewModel by navGraphViewModels(R.id.scan_graph)

It fails at runtime with error Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor

When changing it to "by viewModels()" it works fine and saw there is a HiltViewModelFactory being used.

I found out I can pass a factory to the navGraphViewModels, and it seems that fragment.defaultViewModelProviderFactory is an instance of HiltViewModelFactory; so the following works:

private val scanViewModel: ScanViewModel by navGraphViewModels(R.id.scan_graph) { defaultViewModelProviderFactory }

Is this the way to go? I'm not sure why navGraphViewModels is not using the defaultViewModelProviderFactory by default? Is this a bug in the navigation component (I'm using latest 2.2.x release) ?

Most helpful comment

Yes - val scanViewModel: ScanViewModel by navGraphViewModels(R.id.scan_graph) { defaultViewModelProviderFactory } is correct, we are updating the documentation to mention this while we work on a more seamless integration.

Meanwhile for the duplicate key exception we are tracking it here http://issuetracker.google.com/158737069 and working on a fix.

>All comments

Yes - val scanViewModel: ScanViewModel by navGraphViewModels(R.id.scan_graph) { defaultViewModelProviderFactory } is correct, we are updating the documentation to mention this while we work on a more seamless integration.

Meanwhile for the duplicate key exception we are tracking it here http://issuetracker.google.com/158737069 and working on a fix.

Was this page helpful?
0 / 5 - 0 ratings