what's the correct way to show a toast triggered b...
# compose
l
what's the correct way to show a toast triggered by the viewModel in compose?
🧵 3
✅ 1
d
you shall think in declarative way: UI is a function of state, which means that you have no method "showToast" triggered by VM, but there is parameter e.g. "toastShown" in your state, which VM changes
l
Humm, so the solution would be create a LaunchedEffect with isTostVisible state as a key and show the toast whenever the state is updated to true?
c
@Lucca Beurmann try to keep your message as one single post on slack in order to help with threading conversations. https://kotlinlang.slack.com/archives/CJLTWPH7S/p1612194022136600
✅ 1
d
I expose a
Flow<SideEffect>
and have who ever controls the showing of the
Toast
or
SnackBar
collect it.
SideEffect
being a
sealed class
.
l
Copy code
DisposableEffect(key1 = lifecycleOwner) {
        viewModel.showErrorToast.observeEvent(lifecycleOwner) {
        Toast.makeText(
            context,
            context.getString(R.string.author_details_images_erro
            Toast.LENGTH_SHORT
        )
            .show()
    }
    onDispose {
        viewModel.showErrorToast.removeObservers(lifecycleOwner)
    }
}
Currently that's how i'm observing the viewModel event
d
l
there's a similar example in the SideEffects docs: https://developer.android.com/jetpack/compose/side-effects
but how you are setting up the this flow collection in your composables?
d
Collecting it from a
LaunchedEffect
works fine.
Just ensure that effect is not being called more then once.
l
thanks for the answer
yeah i ensured that my disposable effect is being called just once, my main doubt was how to collect/observe the event from the viewModel
t
If you find yourself needing to show a snackbar instead, check out https://developer.android.com/reference/kotlin/androidx/compose/material/SnackbarHostState
271 Views