Working with LiveData : SingleLiveEvent and imparting states
Hi Everyone !
Introduction
Recently Google introduced MVVM (Model-View-ViewModel) Architecture for android app development so we thought about giving it a shot by implementing it in our OYO Consumer App projects.
Here are some of the new things I observed apart from many others while working as a beginner on MVVM and LiveData. These might be known to some beforehand but I felt these were some really simple and impactful tools one could use while working on MVVM. I would like to thank Sidakpreet Singh Nanda, whose codebase I used to get an idea of how to proceed with the new architecture.
What is LiveData ?
LiveData
is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components (activities, fragments, or services). This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
To know more please visit : https://developer.android.com/reference/androidx/lifecycle/LiveData
LiveData is always up to date and helps in doing away the tight coupling of View and Presenter that we observe in VIPER architecture, no more manual lifecycle handling. The view simply subscribes to changes in LiveData and reacts accordingly.
Problems with constant updation
While implementing the project several instances come up when one needs to use the data once and there is no need for constant updation (like displaying a dialogue box, alert messages, Snackbar etc.) as they might lead to such actions being fired multiple times.
Instead of constantly observing the LiveData or using maintaining different flags, we can fire events. These events can be intercepted by the subscribers (Activity/Fragment) and can change the UI accordingly.
We can create a class file called SingleLiveEvent (essentially a wrapper of the LiveData) in our project as follows :
So for a particular event like :
we can observe it in the main fragment and do the required action :
Imparting states
While working with UI, one comes across scenarios where we feel the need to handle different use cases for the same dataset which could be easily handled if we could impart states to them. Here we can make use of simple classes through enums.
They can be used to associate states to the data thereby creating different events in the ViewModel.
For example, one can create a class called Resource, with 3 distinct states SUCCESS, LOADING and ERROR. These states standalone or in combination to the SingleLiveEvent can be used to tackle the different use cases as illustrated in the example below. Instead of implementing different callbacks/ listeners, we can make use of these states, to make decisions.
Thank you, hope you were able to get an idea about LiveData and some of the ways to tackle generic problems which a beginner might face while working with it.