Android EP2: Understanding Android ViewModel, LiveData - Interview Questions included
A Short but Informative You Need to Know About ViewModel x LiveData: From Basics to Advanced Topics and Interview Tips.
In this post, I’ll cover 3 topics
Android ViewModel and its Lifecycle
Android LiveData
Related interview questions (2023 Updated)
ViewModel & its Lifecycle
ViewModel is an Android architecture Component that is designed as a Data Holder to store and manage UI-related data across Activity / Fragment states regardless of configuration changes, such as users rotating the device screens or changing the app windows. When the app configuration change, Unlike Activity or Fragment, ViewModel instances are not destroyed.
How ViewModel survive across configuration changes?
TLDR;
- Every Activity, Fragment implemented a ViewModelStoreOwner that return the ViewModelStore. ViewModelStore will store the ViewModels to a hashMap with the Key default is ViewModel's canonicalName.
- The ViewModelStore won't be clear when the Activity got destroyed by change configuration (*) (code snippet 1)
- The ViewModelStore will be provided by the last non-configuration Instance of the Activity (**) (code snippet 2)
(*) Code snippet 1
class ComponentActivity
function default constructor
(**) Code snippet 2
class ComponentActivity
function ensureViewModelStore
Android LiveData
LiveData is an observable data holder class. Unlike regular observables such as RxJava Subject, Single or Flowable; Android LiveData is lifecycle-aware, it respects the lifecycle of the observer (Activity, Fragment). This makes sure the Observer of LiveData only updates when it is in an Active State.
Only use LiveData as an observable for UI components because the execution of Observer#onChanged will run on the Main Thread.
Read the detailed document to understand how to work with LiveData
Related Android Interview Questions (2023 Updated)
What advantages of ViewModel in MVVM architecture
ViewModel in MVVM is the container of Business Logic or Use Case of a Fragment or Activity.
ViewModel survived despite configuration changes, it’s a good solution for data holders.
When we use LiveData as the data holder inside a ViewModel, the LiveData instance is lifecycle-aware and will survive despite configuration changes. When the activity or Fragment enters the resumed state, LiveData will automatically update the UI with the latest data, thanks to its lifecycle awareness.
What difference between LiveData & RxJava or Kotlin Flow
LiveData only supports Observe On on UI; RxJava and Kotlin Flow support multiple types of Threads.
LiveData needs a particular lifecycle to bind on; RxJava and Kotlin Flow work globally.
Any solutions to optimize if your Activity or Fragment has too much LiveData
Consider refactoring the codebase to reduce the number of LiveData objects by re-organizing data holders.
Use MediatorLiveData
The Sky is your limit
Happy Coding!