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
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) ?
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.
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.