https://kotlinlang.org logo
s

Shivam Sethi

02/26/2021, 1:49 AM
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

02/26/2021, 1:56 AM
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

02/26/2021, 2:44 AM
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

02/26/2021, 3:49 AM
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

02/26/2021, 5:49 AM
Again thanks @Ian Lake just implemented this approach,
🎉 1