Home > database >  hiltViewModel<ViewModel>() vs by viewModels()
hiltViewModel<ViewModel>() vs by viewModels()

Time:06-20

(This might not be relevant, but I haven't been able to find the answer anywhere and it's been bugging me)

While creating and reviewing applications that use dagger-hilt I noticed that most people, to create an instance of their viewModel class, use something like

val viewModel: XViewModel by viewModels()

and some use

val viewModel = hiltViewModel<XViewModel>() 

is there any difference between those two?

CodePudding user response:

Both will create a view model instance using hilt but the difference is that this one below is for creating view model for a fragment, you can't use it in a composable screen:

val viewModel: XViewModel by viewModels()

And the second one is new and comes with jetpack compose, you can use it inside a composable screen and it will create a view model instance that will stay alive as long as your screen is in navigation stack:

val viewModel = hiltViewModel<XViewModel>() 
  • Related