I have a Login NavGraph which has two screens, A a...
# compose
n
I have a Login NavGraph which has two screens, A and B, both of them are using the same ViewModel, I want to do a popBackStack to navigate back to screen A when an error occurs in screen B, and at the same time screen A triggers the display of a Snackbar to indicate the error, is there any elegant way to do this in this case? 🤔
I tried to use
Channel/SharedFlow
and Collect it on both screens at the same time, but it seems that after navigating to the A screen, the A screen does not collect Error signals A Screen:
Copy code
@Composable
fun LoginA(viewModel: XXX = hiltViewModel()) {
  val navigateEvent by viewModel.navigateEventFlow.collectAsStateWithLifeCycle(initial = null)
  LaunchedEffect(navigateEvent) {
    navigateEvent?.let {
      when (it) {
        is LoginNavigateEvent.LoginException -> {
          snackbarState.show(SnackbarType.Error(it.message))
        }
        else -> Unit
      }
    }
  }
}
B screen:
Copy code
@Composable
fun LoginB(viewModel: XXX = hiltViewModel()) {
  val navigateEvent by viewModel.navigateEventFlow.collectAsStateWithLifeCycle(initial = null)
  LaunchedEffect(navigateEvent) {
    if (navigateEvent is LoginNavigateEvent.LoginException) navController.popBackStack()
  }
}
viewModel:
Copy code
private val navigateEvent = MutableSharedFlow<LoginNavigateEvent>()
val navigateEventFlow = navigateEvent.asSharedFlow()

fun handleError() { navigateEvent.emit(...) }

sealed interface LoginNavigateEvent {
  data class LoginException(val message: String) : LoginNavigateEvent
}
p
Flow collection stops when the NavBackStackEntry enters the stop Life cycle state. That's why you use collectAsStateWithLifecycle