Sharing ViewModel within Jetpack Compose Navigation using Hilt

Hello Androiders,
Shared ViewModel deep dive
Sometimes sharing ViewModel is so important for some use cases that it’s inevitable for the user experience or use case.
If you ever used hilt as a dependency injection tool then you must have used or scene different ways of sharing ViewModel between fragments or navigation graphs.
val someViewModel: SomeViewModel by activityViewModels()
We are initializing our ViewModel in fragment A with the activity’s shared scope. Now if the user wants to share SomeViewModel’s same instance in fragment B, they can repeat the above method of initializing ViewModel and they will be served with the same instance of SomeViewModel in fragment B.
Now, we have a different use case and we want to share our ViewModel among the given navigation graphs, then Hilt provided us with the below mechanism to share
val someViewModel: SomeViewModel by
hiltNavGraphViewModels(R.id.navGraph)
By using the above method you can access the instance of SomeViewModel throughout the navigation graph.
Now by saying all what will we do for jetpack compose? Jetpack compose declarative navigation don’t have the traditional jetpack navigation graphs. So how can you share fragments in a composable world?
Thanks to Hilt for help using us by providing hiltViewModel method.
Let’s see jetpack compose navigation in action.
You can see in the above example, we are using a back stack entry with a given navigation URL to share ViewModel.
Here is my composable function mentioned in the above gist, I am using ViewModel as a parameter coming from the NavHost function.
I always try my best to always design a working example of any topic I explain and keep that tradition alive I am attaching my github project and if you want to study more about jetpack compose navigation, I’ll highly recommend exploring official docs.
I hope this was informative for Compose and Jetpack lovers.
Show some love by clapping and subscribing if you like this article 🙂
See you next time with another android topic 🙂 Bye !!!!
Share this article

Written by : admin
Latest Articles
June 21, 2024
June 11, 2024
June 10, 2024
May 31, 2024
May 27, 2024
May 10, 2024
February 1, 2024
December 28, 2023
December 26, 2023
December 18, 2023
December 15, 2023
September 26, 2023
September 21, 2023
September 19, 2023
September 19, 2023
September 12, 2023
September 5, 2023
August 29, 2023
March 31, 2023
March 20, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023