Hi! I need suggestion on what is the ideal way to ...
# compose-android
a
Hi! I need suggestion on what is the ideal way to store arguments in the viewModel, which were passed to a composable. More in 🧵
My current approach is under. Is this enough or decent?
Copy code
navigation<Graph>(
    startDestination = Screen,
) {
    composable<Screen> { navBackStackEntry ->
        // This is important and will be shared
        val graph: Graph = navController.getBackStackEntry<Graph>().toRoute()
        val viewModel = navBackStackEntry.sharedViewModel<GraphViewModel>(navController)
        // I am adding it with a launched effect
        LaunchedEffect(graph) {
            viewModel.graphData = GraphData( … )
        }
        Screen( … )
    }

    // …
}
s
If the VM is shared already, can that not already have this information populated at the time in which it is constructed? So in the constructor itself?
a
Initially the VM do not have this info. I am using
hilt
, so I was doing this with
@AssistedInject
in the
startDestination
and rest of the destinations used
sharedViewModel
extension. Is that a more better approach?
I do feel like AssistedFactory is indeed better, but I am not sure 🥲 (lack of expertise)
I am wondering if I can pass data to
startDestination
.
Turns out Ican't
s
Isn't the VM scoped to the graph? And doesn't that data exist in that graph destination? Sounds to me like you can grab the data from the graph and give it to the initializer that first creates your VM. Hilt does allow you to provide extra things.
a
Yes, thanks for confirming. I have reverted back to using @AssistedFactory from hilt. I don’t know why, but it seemed like an overdo at the time and I tried to ‘simplify’ it like this. Maybe its just me overthinking about it …
UPDATE: This was indeed an over do and unnecessary. I am using
SavedStateHandle
in my VM and the args can be retrieved via
savedStateHandle.toRoute<MyClass>()
🌟 2