3

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 ?

bob ze
  • 61
  • 3
  • Are you using Navigation? Each route has it's own scope of view models. More info [here](https://stackoverflow.com/a/69002254/3585796) and [here](https://stackoverflow.com/a/64961032/3585796) – Phil Dukhov Jan 25 '22 at 13:23
  • what I am trying to do is this answer here: https://stackoverflow.com/a/50533585/18028117 the problem is, I get the view model in the activity to subscribe to permission requests, but what is actually passed to the compose is a new instance of MyViewModel which is not subscribed to it's Observable/LiveData – bob ze Jan 25 '22 at 14:34
  • Check out [Accompanist Permissions](https://google.github.io/accompanist/permissions/), you don't need a view model to manage permissions – Phil Dukhov Jan 26 '22 at 02:35
  • Amazing! thanks @PhilipDukhov – bob ze Feb 04 '22 at 21:49

1 Answers1

5

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)
}
Altline
  • 193
  • 3
  • 10