How to handle global ui element state and behavior...
# compose
y
How to handle global ui element state and behavior?
Copy code
@Composable
fun MyApp() {
  val appState = rememberMyAppState()

  MyTheme {
    Box {
      AppNavigation(navController = appState.navHostController)

      // TODO add global loading composable here.

      SnackbarHost(
        hostState = appState.snackbarHostState,
        modifier = Modifier.align(Alignment.BottomCenter)
          .padding(bottom = 48.dp),
      )
    }
  }
}
class MyAppState(
  val coroutineScope: CoroutineScope,
  val snackbarHostState: SnackbarHostState,
  val navHostController: NavHostController
) {

  fun showSnackbar(
    message: String,
    actionLabel: String? = null,
    duration: SnackbarDuration = SnackbarDuration.Short
  ) {
    coroutineScope.launch {
      snackbarHostState.showSnackbar(
        message = message,
        actionLabel = actionLabel,
        duration = duration
      )
    }
  }
}
@Composable
fun rememberMyAppState(
  snackbarShowScope: CoroutineScope = rememberCoroutineScope(),
  snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },
  navHostController: NavHostController = rememberAnimatedNavController(),
) = remember(
  snackbarShowScope, snackbarHostState, navHostController
) {
  MyAppState(
    coroutineScope = snackbarShowScope,
    snackbarHostState = snackbarHostState,
    navHostController = navHostController
  )
}
my question is what is the best way to handle the snackbar showing all over my screens? pass the
showSnackbar
function down to every screen? or use a global ViewModel to handle this?
c
I think the way you have it is basically where I'd start. If you want a global snackbar then you pretty much need it at that level. I do something similar to this without any issues FWIW.