ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

SingleLiveEvent to help you work with LiveData and events

--

Photo by Freddy Marschall on Unsplash

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):

SingleLiveEvent class utility
The ViewModel with SingleLiveEvent observable object instead of MutableLiveData
The Fragment in which the ViewModel is created, then the observer is initialized and creates the Dialog

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)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Carlos Daniel

Android & Flutter Developer. GDE for Android & Mobile Engineer.

Responses (6)

Write a response