Photo by Jakob Owens on Unsplash

Android Architecture Components: Handling clicks and single actions in your View Model with LiveData.

Dai
AndroidPub
Published in
2 min readNov 30, 2017

--

If you have started using the new Android Arch components you have probably reached a point and asked, “How do I handle a click or single event in my ViewModel?”. You have probably found this article because you have the same issue I had when trying to handle single events. This is just an idea so feel free to comment about other solutions and your thoughts 💭.

A potential solution. Stateless LiveData.

No one likes a null, so we are going to use it to our advantage here. The idea is simple. I will explain in code first:

So here we are extending the MutableLiveData class, creating our own ActionLiveData class. We then override the observe method, limiting the observers to only one by checking if the LiveData already hasObservers and using the super.observe call passing in a new Observer. The next bit is where we make this work. First we want to ignore null values and early return. If the LiveData value is not null we notify the observer and set the value back to null straight away. This means that the state of the LiveData is always null and the LiveData only ever emits new actions when the value is set again.

Example

View Model

So let’s create a simple ViewModel with the ActionLiveData (as described above) and use for a Snackbar message class .

In this file I have also included a SnackbarMessage data class which we use as our value type. ActionLiveData<SnackbarMessage>.

Activity/Fragment

In your Activity or Fragment, subscribe to the MainViewModel snackBarAction and show a new snack bar every time your receive an event. Set up a simple button and a method on the MainViewModel to be called every time it’s clicked, sending a new Snackbar message.

I used a button here and snack bar in this example, but this action could be the result of anything. It could be a callback to say your data successfully saved to the server. Or that you want to launch a new Activity on click.

Quick tip. If you use Kotlin why not make an extension function to clean up how you get view models. Something like this:

Other Ideas

This is just my idea on how to solve the problem. It’s simple and works for our use case. The hope is that something will eventually be added to the Arch components library to officially support single events in your view model. Search around the internet and you may find a solution on the Google Samples GitHub repository, SingleLiveEvent. There are also some other solutions on the GitHub issue here.

--

--

Dai
AndroidPub

Engineering Manager (Client Platforms) @Plex