Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared view model in android compose project while using Hilt for dependency injection?

Anyone has any clue how to retain a shared view model object across different composables? I'm using hilt and injecting viewmodel instance using hilt in composable. Basically there are 3 screens which share same data and changes I want to share it and I'm thinking of sharing this data through a shared view model.

myViewModel: MyViewModel = hiltViewModel()

So how can i use this MyViewModel as shared view model?

like image 665
Ali Nawaz Avatar asked Feb 04 '26 20:02

Ali Nawaz


2 Answers

All you need is something like this to find the view model in your navigation back stack entry and pass it to next composable screen:

val backStackEntry = remember {
    navHostController.getBackStackEntry("first_screen_route_where_viewmodel_was_firstly_initialized")
}
val viewModel: MyViewModel = hiltViewModel(backStackEntry)

Now you have got the view model which is exactly at same state where you have left it in previous screens. Now you can use it as a shared view model. Thanks @Pylyp for guidance..

like image 151
Ali Nawaz Avatar answered Feb 06 '26 12:02

Ali Nawaz


As per the official documentation:

If you need to retrieve the instance of a ViewModel scoped to navigation routes or the navigation graph instead, use the hiltViewModel composable function and pass the corresponding backStackEntry as a parameter:

import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.getBackStackEntry

@Composable
fun MyApp() {
    NavHost(navController, startDestination = startRoute) {
        navigation(startDestination = innerStartRoute, route = "Parent") {
            // ...
            composable("exampleWithRoute") { backStackEntry ->
                val parentEntry = remember(backStackEntry) {
                    navController.getBackStackEntry("Parent")
                }
                val parentViewModel = hiltViewModel<ParentViewModel>(parentEntry)
                ExampleWithRouteScreen(parentViewModel)
            }
        }
    }
}
like image 29
gabhor Avatar answered Feb 06 '26 13:02

gabhor



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!