0

I have created a bottom navigation bar in which i have three fragments, for now,let's say fragment 1, 2 and 3. I have enabled a live data observer and it shows a message whenever an api returns the error message. The message is then shown to the user via the snackbar. I had some issues while showing the messages as my app was crashing. I have rectified the error.

The app is no more crashing but I ran into another problem. Let's say there is an error message "User not found" in fragment 3. The message is displayed in the snackbar. But when I navigate back to the fragment 1 or 2, the same error message is displayed in the snackbar. I have checked the api response and there is no error response.

private val errorObserver = Observer<Int>{
activity?.let { it1 -> Snackbar.make(it1.findViewById(android.R.id.content), it, Snackbar.LENGTH_SHORT).show() }}

This is the code I used to solve the initial problem of crashing. I don't know how to solve the second one.

2

1 Answer 1

0

Your problem is probably (you haven't posted much code) that you're holding your error state in something like a LiveData or StateFlow. When your Fragments start and begin observing that error state, if there's a current value then the observer receives that immediately, and handles it (e.g. by showing a Snackbar).

This is fine when your UI is meant to be updating to display the current state, but it seems like your errors are an event, something transient that occurs and then goes away. You basically need to clear that error value once it's handled, so that anything that observes that observable won't see that same error.

People in the comments are mentioning the SingleLiveEvent approach, but that's an old workaround that the Android team considers an antipattern now. The recommended way of consuming UI events is explained here, but it basically goes like this:

  • In a ViewModel, some UI state object (e.g. an error state, or an object describing the entire UI with an error state field in it) updates to hold an error value
  • an observer sees this change, handles the error (e.g. displaying a message), and then tells the ViewModel the error event has been consumed
  • the ViewModel updates the error state / UI state again with the "no error" state, or whatever (maybe the next error if there's a queue of them)

So in your case, as soon as you display the snackbar, you'd tell the ViewModel (or however you're doing things) to clear that error, because it's an event that's been handled. This is different from a persistent error state, e.g. showing a warning icon if there's a problem that needs addressing, which you'd want to show all the time (until that error state changes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.