How to put snackbar button response in one suspend function in Kotlin jetpack

22 views Asked by At

How to put snackbar button response in one suspend function in Kotlin jetpack. I have one SnackbarResult.ActionPerformed for all my snackbars. And I have suspend fun for my snackbar:

suspend fun snackBar(
    snackbarHostState: SnackbarHostState, context: Context,
    buttonText: Int = settings,
    snackbarText: Int = permission_access
) =
    snackbarHostState.showSnackbar(
        context.resources.getString(snackbarText),
        context.resources.getString(buttonText),
        duration = SnackbarDuration.Short
    )

Now I need to call this function like:

val contextSnackBar = LocalContext.current as ComponentActivity
snackBarScope.launch {
when (snackBar(context = context, snackbarHostState = snackbarHostState)) {
     SnackbarResult.ActionPerformed -> {
          contextSnackBar.appSettings().apply {
          contextSnackBar.startActivity(this)
          }
      }
}

But how can I put SnackbarResult.ActionPerformed in my suspend function?

1

There are 1 answers

0
BenjyTec On BEST ANSWER

As pointed out in a comment, check out the showSnackbar documentation:

suspend fun showSnackbar(
    message: String,
    actionLabel: String? = null,
    withDismissAction: Boolean = false,
    duration: SnackbarDuration = if (actionLabel == null) SnackbarDuration.Short else SnackbarDuration.Indefinite
): SnackbarResult

It returns a SnackbarResult which is

SnackbarResult.ActionPerformed if option action has been clicked or SnackbarResult.Dismissed if snackbar has been dismissed via timeout or by the user

So this will set the SnackbarResult automatically, you do not have to set it manually. Whenever the user clicks on the action that you defined via actionLabel, the function will automatically return SnackbarResult.ActionPerformed.