https://kotlinlang.org logo
#compose
Title
# compose
z

zsperske

11/29/2021, 9:38 PM
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

Ian Lake

11/29/2021, 10:04 PM
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

zsperske

11/29/2021, 11:08 PM
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!
7 Views