Jetpack Architecture Components in Android
Android Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single modular entity. Nowadays, nearly 99% of the apps present on the Google Play Store uses Android Jetpack libraries. Moreover, to deal with changes/updates in data and application lifecycle, Google introduced Architecture components. This article explains each and every library of this component in detail. Jetpack consist of a wide collection of libraries that are built in a way to work together and make robust mobile applications. Its software components have been divided into 4 categories:
Further, Architecture Components could be classified as follows:
- Room
- WorkManager
- Lifecycle
- ViewModel
- LiveData
- Navigation
- Paging
- Data Binding
Android Jetpack with its architecture component defines some key principles which one should follow as a secure path to develop good and robust mobile apps. It does not support any particular architecture pattern but suggests a clear separation of concerns and controlling of UI from Model. By following these rules, developers can avoid problems related to lifecycle and it will be easy to test and maintain the application.
Following are the architecture component’s element and their responsibilities
- The View layer is represented by the Activity/Fragment. They only deal with user interaction and observes as well as exhibits the LiveData element which is taken from the ViewModel.
- ViewModel keeps a check on the Lifecycle of View and is responsible for maintaining data consistency during configuration changes in the device or other android lifecycle events.
- The Repository is a class with no proper implementation and is responsible for gathering data from all the sources. It handles all the data and transforms them into observable LiveData and makes it accessible to ViewModel.
- Room is an SQLite mapping library that overcomes the challenges of SQLite database like writing boilerplate codes, and query checking at compile time. It has the ability to return queries directly with observable LiveData.
Ways to include Android Jetpack libraries in the application
- Add google repository in the build.gradle file of the application project.
buildscript {
repositories {
google()
mavenCentral()
}
- All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
allprojects {
repositories {
google()
mavenCentral()
}
}
Architecture Components
1. Room Component
The requirement of a database in Android is fulfilled by SQLite from the very beginning. However, it comes with some severe drawbacks like not checking the queries at compile-time, it does not save plain-old-Java Objects(commonly referred to as POJOs). Developers also need to write a lot of boilerplate code to make the SQLite database work in the Android OS environment. The Room component comes into the picture as an SQLite Object Mapping Library which overcomes all the mentioned challenges. Room converts queries directly into objects, check errors in queries at the compile-time, and is also capable of persisting the Java POJOs.
Moreover, it produces LiveData results/observables from the given query result. Because of this versatile nature of the Room component, Google officially supports and recommends developers to use it. The Room consists of the following sub-components:
- Entity: It is the annotated class for which the Room creates a table within the database. The field of the class represents columns in the table.
- DAO(Data Access Object): It is responsible for defining the methods to access the database and to perform operations.
- Database: It is an abstract class that extends RoomDatabase class and it serves as the main access point to the underlying app’s relational data.
Advantages of Room Component:
- Reduce boilerplate code
- Simplifies database access mechanism
- Easy to implement migrations
- Test-ability is high
2. WorkManager
WorkManager API provides an optimal solution to manage the background tasks in Android which are deferrable(can be run later and is still useful) as well as guaranteed(runs even if the device restarts) in nature. Its capability to cover the power-saving feature of Android and the ability to run with or without Google Play Services are the reasons for its popularity among developers. Further, it is also backward compatible with API level 14.
The ability of android devices to download a file/document in chunks i.e., occasionally(like user resumes download as per the availability of the WiFi Network) and the feature of saving the downloaded state even if the device restarts is possible only because of WorkManager API. Its execution of tasks depends upon the order of requests made by the user and for each work request, it returns the state which is displayed on the UI of the device.
Advantages of WorkManager Component:
- Provides backward compatibility
- Scheduling and chaining of tasks is possible
- Users can keep track of/status of the tasks.
3. Lifecycle-Aware Components
Details of the lifecycle state of an android component are stored in the Lifecycle class and it permits other components/objects to observe this state. An android component is lifecycle-aware if it has the ability to detect the change in the lifecycle state of other components and respond accordingly. Proper management of application lifecycles is a challenging task for the developers as it can lead to severe issues like memory leaks and app crashing. The android.arch.lifecycle package facilitates the developers by managing the lifecycles attached to the components directly by the system. By implementing the LifecycleObserver interface within the desired class, it can be configured to be lifecycle-aware.
There are 2 ways to create Activity / Fragment which are Lifecycle aware:
- Extend a LifecycleActivity or LifecycleFragment
class MainActivity : LifecycleActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
- Connect LifecycleObserver and Lifecycle events through annotation
class MainActivityObserver : LifecycleObserver, AnkoLogger {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
info(“onResume”)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
info(“onPause”)
}
}
Advantages of Lifecycle-Aware Components:
- Helps in creating organized application components
- Ease in testing and maintenance of components
- Less code requirement to executes tasks
4. ViewModel
ViewModel is one of the most critical classes of the Android Jetpack Architecture Component that support data for UI components. Its purpose is to hold and manage UI-related data. Moreover, its main function is to maintain the integrity and allows data to service during configuration changes like screen rotations. Any kind of configuration change in Android devices tends to recreate the whole activity of the application. It means the data will be lost if it has been not saved and restored properly from the activity which was destroyed. To avoid these issues, it is recommended to store all UI data in the ViewModel instead of an activity.
An activity must extend the ViewModel class to create a view model:
class MainActivityViewModel : ViewModel() {
………
……..
}
Advantages of ViewModel Component:
- Helps in data management during configuration changes
- Reduce UI bugs and crashes
- Best practice for software design
5. LiveData
This component is an observable data holder class i.e, the contained value can be observed. LiveData is a lifecycle-aware component and thus it performs its functions according to the lifecycle state of other application components. Further, if the observer’s lifecycle state is active i.e., either STARTED or RESUMED, only then LiveData updates the app component. LiveData always checks the observer’s state before making any update to ensure that the observer must be active to receive it. If the observer’s lifecycle state is destroyed, LiveData is capable to remove it, and thus it avoids memory leaks. It makes the task of data synchronization easier.
It is necessary to implement onActive and onInactive methods by LiveData:
class LocationLiveData(context: Context)
: LiveData<Location>(), AnkoLogger, LocationListener {
private val locationManager: LocationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
override fun onActive() {
info(“onActive”)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, of, this)
}
override fun onInactive() {
info(“onInactive”)
locationManager.removeUpdates(this)
}
// ….
}
In order to observe a LiveData Component observer(LifecycleOwner, Observer<T>) method is called:
fun observeLocation() {
val location = LocationLiveData(this)
location.observe(this,
Observer { location ->
info(“location: $location”)
})
}
}
Advantages of LiveData component:
- UI is updated as per the appropriate change in the data
- It removes the stopped or destroyed activities which reduce the chance of app crash
- No memory leaks as LiveData is a lifecycle-aware component.
6. Navigation Component
The navigation component of Android architecture is a framework for designing the in-app UI. Developers can follow the single-activity app architecture to structure the application UI. Navigation manages the complexity related to the fragment transactions in the application. It also facilitates developers to display transitions and Back behavior.
By using the Navigation Component, one can get all the benefits of other Architecture components as well like Lifecycle and ViewModel. It helps in implementing basic navigation styles like simple button clicks to complex navigation patterns like app bar and navigation drawer. Further, it also supports deep links and helpers which enables the connection of this component with the navigation drawer and bottom navigation.
Advantages of Navigation Component:
- Ease the transition through animated visualization
- Supports deep linking
- Handle fragment transactions
- Support common as well as a complex navigation pattern
7. Paging
While developing an android application, it is very much important to organize the data loading process. Mostly, apps display one activity/fragment at a time and thus require to load and display only a small section of data. However, at the same time, the application is processing a large dataset that is currently of no use. Thus, it is a critical area of the application which must be handled, otherwise can lead to waste of the device’s battery and the network bandwidth.
The Paging library of the Android architecture component provides the optimal solution to these issues. This library provides the facility to load the application data slowly and in a cautious manner. Moreover, paging is a very cooperative library for those applications in which the displayed data is updating continuously as it provides a list of unbounded sites as well as large but bounded lists. Following are the three common ways of loading data through the paging library:
- Loading data is stored in the device database
- Loading data over a network by serving as a cache for the database
- Load data by serving from the back-end server
Advantages of Paging component:
- Easy to integrate with Recycler View in order to display a large data set.
- Compatible with LiveData and RxJava for updating the UI data
- Loads data gradually with caution
8. Data Binding
Data Binding library is a support library that provides the feature of binding UI components in an activity/fragment to the data sources of the application. The library carries out this binding task in a declarative format and not in a programmatical way. Below is an example to understand the working of this library accurately:
To find a TextView widget and bind it to the userName property of the ViewModel variable, the findViewById() method is called:
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
After using the Data Binding library, the above code changes by using the assignment expression as follows:
<TextView
android:text=”@={viewmodel.userName}” />
Advantages of Data Binding Component:
- Make code simpler and easy to maintain by removing UI frameworks called in the activity.
- Allows classes and methods to observe changes in data
- Allows to make objects and filled which works as collection observable.
Code snippet to add jetpack architecture components such as LiveData and ViewModel:
dependencies {
def lifecycle_version = “2.3.1”
implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”
…
}
Contact Us