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

Young Rock

06/30/2022, 6:55 AM
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

Colton Idle

06/30/2022, 2:24 PM
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.
79 Views