Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity view model in Jetpack compose

In fragment, we have

private val activityViewModel: MainActivityViewModel by activityViewModels()
private val fragmentViewModel: MainFragmentViewModel by viewModels()

to get an instance of a shared view model throughout the app (activity view model) and a view specific view model (fragment view model).

I am migrating to compose.

How to get two view models with different scopes in jetpack compose?

From the docs, I can see this line,

viewModel() returns an existing ViewModel or creates a new one in the given scope.

But, how do I specify the scope of the view model?

P.S.
I have already gone through this question which is similar but it doesn't have any answers.

like image 670
Abhimanyu Avatar asked Jun 11 '26 22:06

Abhimanyu


1 Answers

Normally within a single composite tree, such as within the setContent content, there is one view model scope that is shared between all child composites.

You can override it if you want, using LocalViewModelStoreOwner:

CompositionLocalProvider(
    LocalViewModelStoreOwner provides viewModelStoreOwner
) {
    NextComposable()
}

Compose Navigation overrides it for each navigation destination. See this answer to see how you can share it between navigation destinations.

like image 158
Philip Dukhov Avatar answered Jun 16 '26 14:06

Philip Dukhov



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!