SingleLiveEvent to help you work with LiveData and events

Have you had to deal with a Dialog or a SnackBar that after been triggered/shown or dismissed and followed by a device rotation is triggered/shown again? Probably this has to be related to the use of LiveData observables to communicate the ViewModel and the Activity/Fragment.
This is good, but the main woe here is that it will be observing continuously, however for this particular cases, need to be consumed only once.
The Anti-Pattern
Using LiveData objects for events can be taken as a bad design decision, even more when that event needs to be consumed just once. We can have a workaround using some boolean flags to help the view decide whether the Dialog/SnackBar must be triggered/shown or not. But this can lead to a solution difficult to read/maintain and ugly as well.
Using SingleLiveEvents as a solution
For his particular scenarios, SingleLiveEvent class was created to solve the problem. The updated value is sent only once, just as needed. And its use is rather easy, just like using a LiveData (in fact it’s an extension of MutableLiveData):
And that is all. Take a look of line 7 within the last snippet. auctionsViewModel.getUploadAuction().observe() will observe only once because getUploadAuction() returns only one value, then stops observing. And this solves the problem we were stating at the beginning.
For more details regarding patterns and anti-patterns while using ViewModels and LiveData as well as to have a deep explanation about SingleLiveEvent, you may want to take a look of this two resources from Android Developers:
1. ViewModels and LiveData: Patterns + AntiPatterns
2. LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)