Assigned
Status Update
Comments
da...@google.com <da...@google.com> #2
Sorry, there is no convenient Hilt 'by lazy' API that takes a key because the
You can create your own though:
inline fun <reified VM : ViewModel> Fragment.hiltNavGraphViewModels(
key: String,
@IdRes navGraphId: Int
): Lazy<VM> = lazy {
val backStackEntry = findNavController().getBackStackEntry(navGraphId)
ViewModelProvider(
owner = backStackEntry,
factory = HiltViewModelFactory(requireActivity(), backStackEntry)
).get(key, VM::class.java)
}
rd...@gmail.com <rd...@gmail.com> #3
Thank you very much. This solves my much needed requirement.
Description
Component used: hilt-navigation-fragment
Version used: 1.2.0
This is my first time posting, and I apologize in advance for lack of in-depth knowledge and error in following any format.
I've been looking for a way to create a separate instance of my viewmodel via hilt for each of the fragments hosted in a viewpager. However, the viewmodels must be scoped to the parent fragments nav graph. Currently doing so via the following method, returns the same viewmodel instance for all fragments which is not desired.
I noticed the compose API provides this feature to pass a custom key in
After digging through the code, I found out the both approaches use ViewModelProvider to create a the ViewModel instance however, for fragments we're unable to pass a custom Key as opposed to Compose.
Is there a way I can currently create my ViewModels via hilt + navigation but with a custom key?