Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hiltViewModel from Activity?

I am trying to get a view model in two places, one in the MainActivity using:

val viewModel:MyViewModel by viewModels()

The Other place is inside a compose function using:

val viewModel:MyViewModel = hiltViewModel()

When I debug, it seems that those are two different objects. Is there anyway where I can get the same object in two places ?

like image 208
bob ze Avatar asked Dec 30 '25 13:12

bob ze


1 Answers

Even though you solved your issue without needing the view model, the question remained unanswered so I am posting this in case someone else finds it helpful.

This answer explains how view model scopes are shared and how you can override it.

In case you are using Navigation component, this should help. However, if you don't want to pass down view models or override the provided ViewModelStoreOwners, you can access the parent activity's view model in any child composable like below.

val composeView = LocalView.current
val activityViewModel = composeView.findViewTreeViewModelStoreOwner()?.let {
    hiltViewModel<MyViewModel>(it)
}
like image 140
Altline Avatar answered Jan 02 '26 11:01

Altline



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!