bob ze
bob ze

Reputation: 61

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 ?

Upvotes: 3

Views: 4581

Answers (2)

Amit Kundu
Amit Kundu

Reputation: 119

Adding with @Altline.

In the following way we can get non null viewmodel in the compose view

val context = LocalView.current
val mainViewModel by lazy {
    ViewModelProvider(context as ViewModelStoreOwner).get< MyViewModel >()
}

Upvotes: 0

Altline
Altline

Reputation: 383

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)
}

Upvotes: 9

Related Questions