How do you handle navigation in Jetpack Compose wh...
# compose
n
How do you handle navigation in Jetpack Compose when it depends on business logic (e.g., an API response)? Currently, we pass navigation lambdas from the UI to the ViewModel and call them there based on the logic. Is this a good approach, or is there a better way to manage this?
a
Its okay approach. If you make sure your state holder, lambda user does not outlive the navigator then u are fine.
c
I’d say it’s a bad approach. The request should trigger a state change and depending on that you navigate in the ui layer.
n
Is there any guidance or best practices we should follow for this? It would be helpful to understand the recommended approach for handling navigation in Jetpack Compose when it’s driven by business logic, especially in scenarios like API responses.
c
It’s basically “separation of concerns” - nothing compose special. Why would the viemodel need to know anything about navigating in your ui? https://en.m.wikipedia.org/wiki/Separation_of_concerns
👍 1
n
I noticed this approach being used in the JetSurvey app, which was once part of the official Jetpack Compose samples. However, I’m unable to find the app in the repository anymore: https://github.com/android/compose-samples/blob/main/Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/signinsignup/WelcomeViewModel.kt. It seems to have been removed.
I agree that separation of concerns is important, and the ViewModel should focus on business logic rather than navigation. However, navigation is often driven by state changes, especially in cases like API responses. I’m curious about the best approach to trigger navigation without tightly coupling it to the ViewModel. Should the UI layer handle navigation by observing state changes, or is there a more effective pattern in Compose to manage this flow cleanly?
c
Maybe this helps. There is a example to handle log in state https://developer.android.com/topic/architecture/ui-layer/events#handle-viewmodel-events
👍 1
a
Why is it a bad approach? Why cant you change navigation state from viewmodel through a method belonging to an interface implementing navigation state change?
Id say it okay, and neither the view nor its viewmodel has to know about navigation implementation, if they interact through the interface, dont see any high coupling here.
z
@Chrimaeon I read somewhere that it is bad practice to make state trigger events like click etc.