Might be a basic question but how do I display rep...
# compose-android
a
Might be a basic question but how do I display repeated Toast/Snackbar with the same message? I have an Exception and I want to display a Toast always for that kind of Exception. The Exception has the same message always, so that's probably the reason why it's not being shown again as a Toast...I've seen the tivi app and it has a
UiMessage
class that wraps a message meant for Toasts/Snackbars together with a random UUID, are there any other ways?
m
For snackbar's I avoid having the UI autohide the snackbar after a given amount of time. That is instead managed by the view model that can reset the time if the event happens again, or switch to a different error if something else should be displayed. That way the existence of a snackbar is just normal state like anything else one the UI. This avoids needing to create solutions for one shot events, which I never felt worked well with MVI, but there were lots of examples of doing it with LiveData. It also falls more into the design of Compose where the UI is driven by state and not events. I'm not as sure about toasts since they are meant to persist between screens and even when the app is in the background. I imagine it can still be handled in a similar way, but you would need your own toast manager and not trigger them from compose itself. I haven't used a toast in years, so I'm not sure the common practice for it.
f
the recommended way to handle these one-off events is to model them as state. Have your state contain the message to display in the toast; when the message is cleared, notify the viewmodel, so that the state can be updated (setting the message to
null
). Once a new toast needs to be displayed, set the message in the state to the new prompt. In the UI you would have a
LaunchEffect
keyed on the message itself.
a
when the message is cleared, notify the viewmodel, so that the state can be updated (setting the message to
null
)
@Francesc I think this was the part that I was missing--I wasn't clearing the toast message in my state data class after showing the Toast. Thanks!