if when composable recomposes everything gets recr...
# compose
h
if when composable recomposes everything gets recreated inside that composable where should I keep reference to my viewmodel?
p
I do it as an input parameter. Also I just reference it at the top most screen. Sub sections of the screen will have its own State class, good for testability and previews
h
@Pablichjenkov is it considered good practice to initialise all viewmodels in the activity and pass the reference all the way down. Like this: Activity-> Navigation graph class composables - > actual composables
p
In general you want the
Android ViewModel
just to host your
composable State
to survive configuration changes. Then in the ‘Navigation graph class composables’ you extract your State from the Android ViewModel and pass that State down to the composables by sections. Don’t pass the root State to child composables, split you big State in child States too, and pass that child State to the child composable. It makes the composable easier to test and preview. You can see in the link below an example of using Android ViewModel as a State holder with the use of hilt. https://github.com/pablichjenkov/ComposeStudy/blob/04298ca8393d3eea0f5b7883fb22316[…]src/main/java/com/pablichj/study/compose/home/HomeNavigation.kt In other platforms like iOS or Desktop they might call
ViewModel
what we call
State
. The reason is those platforms don’t have the term stolen like we have in Android. But my Advice is just use the
Android ViewModel
as a configuration change persister rather than a real ViewModel that contains UI and Domain logic. Place that logic in your State.
h
thank you very much for explanation