How do I make the decision on where to navigate ou...
# compose
z
How do I make the decision on where to navigate outside of my composable? Say I have some card:
Copy code
Card(onClick = { viewModel.postEvent(EventListUIEvent.EventSelected(eventState.event)) } )
I want to make a decision on where to go next without my composable knowing about its potential destinations.
i
Your composable should never know about Navigation at all as per the Testing guide: https://developer.android.com/jetpack/compose/navigation#testing
The State and Jetpack Compose page talks a a bit about how the general approach is to route state down your composable hierarchy and events up your composable hierarchy
In the case of Navigation Compose, that lifecycle is tied to the composition of the NavHost and its NavController - a case of the 'Composables as a source of truth' model. ViewModels have a longer lifetime than your composition (they survive configuration changes, your screen being put on the back stack, etc.), so you can't reference objects tied to a shorter lifetime
It sounds like what you actually want is the 'State holders as the source of truth' - something that exists in the context of composition that can translate events like your onClick through business logic into events that can be sent up the composable hierarchy to your NavHost layer, which would then be the one to actually call
navigate
z
ok interesting, I think I’m following. Thank you for the references to the docs! It’s awesome how much they have improved since I was first trying compose out a year ago. In my situation I’m using KMP to share my view models & business logic between iOS (swiftUI) and Android (compose). SwiftUI has this concept of a “navigation link” where you can tie your conditional navigation to a value like so
Copy code
NavigationLink(destination: EventView(), tag : "event", selection : $viewModel.state.eventDestination)
It feels like this API makes testability difficult (per the testing guide link you shared) but I find myself having to support what I’ve been given. Thanks for the pointers!