s

    Shivam Sethi

    1 year ago
    also is there a way we can scope a ViewModel to certain number of composables using compose navigation library, like we can scope in activity or nav graph for multiple fragments I want to use same ViewModel for 2 screens composables ?
    i

    Ian Lake

    1 year ago
    Navigation Compose does supported nested graphs and does support calling
    getBackStackEntry(routeOfYourGraph)
    Which you can then use like
    val sharedViewModel : MyViewModel = ViewModelProvider(graphBackStackEntry).get()
    Or if you're just trying to return a result, use the APIs for that already: https://developer.android.com/guide/navigation/navigation-programmatic#returning_a_result (they work fine in Navigation Compose)
    s

    Shivam Sethi

    1 year ago
    thanks for these options.
    What I ended up doing to share viewmodel across my navhost composables is just passed in viewmodel as a parameter to my app navigator composable which sets up the destinations
    i

    Ian Lake

    1 year ago
    If you are creating a ViewModel outside of the NavHost, it is essentially scoped to your containing activity/Fragment and therefore lives for the entire lifetime. Not sure if that's actually what you want
    Even just scoping to the root graph's
    NavBackStackEntry
    would at least remove the ViewModel when you dispose of the
    NavHost
    /
    NavController
    s

    Shivam Sethi

    1 year ago
    Again thanks @Ian Lake just implemented this approach,