Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

by viewmodels versus hiltviewmodel

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?

like image 928
james Avatar asked Mar 16 '26 08:03

james


1 Answers

by viewModels():

  1. property delegate.
  2. the first time create, next time return the same instance(in the same scope, the scope is the same activity)

= hiltViewModel():

  1. only used in @Composable annotated function.
  2. the first time create, next time return the same instance(in the same scope, the scope is NavGraph, if no graph, fragment/activity)

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.

like image 153
JeckOnly Avatar answered Mar 17 '26 22:03

JeckOnly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!