When I want to share a view model between various views I would use by viewmodels. I recently began looking into hilt and was wondering if hiltviewmodel would accomplish the same thing? That is to allow me to share a single(same instance) of a viewmodel?
by viewModels():
= hiltViewModel():
you 'd best build a demo and practise it, and log the instance to see if the same instance.
val viewModel: ViewModelA by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HiltDemoTheme {
val viewModel2: ViewModelA = hiltViewModel()
val viewModel3: ViewModelA = viewModel()
val viewModel4: ViewModelA by viewModels()
Log.d("Jeck", "$viewModel")
Log.d("Jeck", "$viewModel2")
Log.d("Jeck", "$viewModel3")
Log.d("Jeck", "$viewModel4")// the four get the same instance
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
}
}
}
Documentation: Hilt and Navigation
When using Navigation Compose, always use the hiltViewModel composable function to obtain an instance of your @HiltViewModel annotated ViewModel. This works with fragments or activities that are annotated with @AndroidEntryPoint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With