When Navigating with Nested Graphs in Compose usin...
# compose
a
When Navigating with Nested Graphs in Compose using Hilt, why does my savedStateHandle not contain the navigationArg? Code in 🧵.
In my composable, when I when i would reference the viewmodel, my viewmodel correctly receives the id.
Copy code
@HiltViewModel
class EditObjectViewModel @Inject constructor(private val savedStateHandle: SavedStateHandle, private val repository: Repository) : ViewModel(){

    val object = savedStatHandle.get<long>("objectId")?.let {
        repository.getObject(it)
    }
}
In the composable I simply had
Copy code
@Composable
fun ObjectCard(editObjectViewModel : EditObjectViewModel = hiltViewModel()){
}
and in the NavHost
Copy code
composable(route, arguements = listOf(navArgument("objectId){ type = NavType.LongType}) { backstackEntry -> backStackEntry.arguemnts?.getLong("objectId") ...}
This works and the viewmodel gets the parameter, however when i define the viewmodel in the navigation graph so I can move it to the nested subgraph scope, the viewmodel no longer correctly gets the id.
Copy code
val editObjectViewModel = hiltViewModel<EditObjectViewModel> (navContrller.getBackStackEntry(nestedGraphRoute))

EditObjectScreen(editObjectViewModel)
c
There's been some problems with savedState in nav. Downgrade to alpha04 of nav and see if it goes away.
a
I currently am on alpha04 of nav. It might be due to the fact that the viewmodel is scoped to the route and not to the composable itself, so when the parameter is passed through as a navigation arg to the composable, the viewmodel is never aware of it occurring due to it already being made. Atleast that is my speculation
i
The ViewModel is scoped to exactly what you said you wanted it scoped to: your navigation graph. That means it knows nothing about arguments attached to a destination inside that graph
a
Thanks for confirming my thought process!