Navigation after API success in Now in Android architecture #2091
Replies: 1 comment 1 reply
-
|
In the Now in Android architecture, the recommended way to handle "one-time" side effects like navigation is to treat the navigation intent as a part of the UI state that must be explicitly "consumed" to prevent repeated triggers on recomposition or configuration changes. 1. Update UI StateAdd a specific trigger (e.g. data class AuthUiState(
val navigateToOtp: Boolean = false,
val isLoading: Boolean = false,
val error: String? = null
)2. ViewModel LogicWhen the API succeeds, update the state. Also, provide a function to "consume" or reset this trigger. class AuthViewModel(...) : ViewModel() {
fun onNavigationHandled() {
_uiState.update { it.copy(navigateToOtp = false) }
}
}3. UI Implementation (Compose)Observe the trigger using @Composable
fun AuthRoute(onNavigateToOtp: () -> Unit, viewModel: AuthViewModel) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
LaunchedEffect(uiState.navigateToOtp) {
if (uiState.navigateToOtp) {
onNavigateToOtp()
// Reset the state to prevent re-triggering on recomposition or process death
viewModel.onNavigationHandled()
}
}
}This approach maintains a Single Source of Truth and avoids the common pitfall of mixing navigation logic directly into the business logic layer. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone,
I’m currently building a project inspired by the Now in Android architecture and had a question about navigation and handling API results.
Context
In my authentication flow:
auth/otp) is sent from the ViewModelCurrent approach
Right now, I observe the UI state in Compose and trigger navigation like this:
Concern
This approach doesn’t feel fully aligned with the Now in Android principles. It mixes UI state with navigation side effects and might lead to repeated navigation on recomposition.
Question
What would be the recommended way to handle this in the Now in Android architecture?
SharedFlow)?I’d really appreciate any guidance or examples from the NIA approach.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions