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

Tgo1014

10/12/2021, 7:40 AM
What’s the proper way to show an one time even? For example a toast from a
SharedFlow
?
c

Csaba Kozák

10/12/2021, 7:41 AM
You should use a side-effect composable for that.
LaunchedEffect
is perfect for this. See this example.
t

Tgo1014

10/12/2021, 7:44 AM
My concern is the “collecting” part. So I should make an if to see if the flow has some value and then launch the toast? I see the scaffold have some snaback state, but what about something else that doesn’t have this state ready for you?
c

Csaba Kozák

10/12/2021, 8:01 AM
You can add a
SnackbarHost()
outside of a
Scaffold
as well.
d

Damian Zawadzki

10/12/2021, 8:02 AM
you can pass any key you want to launched effect, but not sure how null key for instance would work with recompositions. I got one snippet for vm in mvi architecture that collects effects in compose:
Copy code
LaunchedEffect(key1 = "PackagesStartFormEffects") {
                viewModel.effect.collect { effect ->
                    val message = when (effect) {
                        PackagesStartFormContract.Effect.FormConfirmed -> {
                            "Form confirmed!"
                        }
                        is PackagesStartFormContract.Effect.UnknownError -> {
                            effect.message ?: "Unknown error."
                        }
                    }
                    snackbarHostState.showSnackbar(
                        message = message,
                        actionLabel = label,
                        duration = SnackbarDuration.Long
                    )
                }
            }
but it feels like ""PackagesStartFormEffects" is not elegant solution to fulfill the key1 parameter requirement. I think that passing null would do same thing.
👍 1
🤔 1
I've found some other example of key parameter by searching for @Csaba Kozák suggestion here: https://developer.android.com/reference/kotlin/androidx/compose/material/SnackbarHostState
Copy code
val channel = remember { Channel<Int>(Channel.Factory.CONFLATED) }
LaunchedEffect(channel) {
    channel.receiveAsFlow().collect { index ->
        val result = snackbarHostState.showSnackbar(
            message = "Snackbar # $index",
            actionLabel = "Action on $index"
        )
here is channel as parameter.
🙌 1
t

Tgo1014

10/12/2021, 8:10 AM
I guess in this last document I found what as was doing wrong. Instead of
collectAsState()
the example just
collect{}
and do what’s needed
👍 1
4 Views