Search code examples
android-jetpack-composeviewmodelandroid-mvvm

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?


Solution

  • 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..