Android Jetpack Library Manual: Toolkit To Speed Up Your Development Process

282 Views
|
20 Jul 2018
|
5 min
author avatar
Sergey L.
Copywriter

Android developers always try to use specific tools that help them solve various tech tasks during the development process. Such tools may accelerate the process of app building and prevent from making a large number of possible bugs. And here we would like to write about one tool our Android developers actively use - Android Jetpack. Let's check out what this tool is and how to use it properly for Android app development.  

What is Android Jetpack library?

It is a toolkit that is used by our developers to create Android apps for a short period of time without making much effort. This pack includes libraries and special guide. Jetpack has special components that connect the so-called Support Library and Architecture Components. There are four categories that are formed from components mentioned below like Architecture, UI, Foundation, and Behavior.

Android Jetpack library

Structure of Android Jetpack

!

See how Flutter can compete with React Native. Read Flutter vs React Native: which is worth spending your time on as a developer?

In addition, Jetpack was enriched with a few new components recently: WorkManager, Navigation, Paging, Slices, and Android KTX. 

ViewModel as the main library component

The goal of ViewModel component is to store and manage data related to view. Also, it should help developers avoid problems related to activity recreation during such operations like screen rotation.  

ViewModel is an abstract class with only one protected method. 

public abstract class ViewModel  {
     @SuppressWarnings("WeakerAccess")
   protected void onCleared()  {
   }
}

To implement ViewModel, it is necessary to inherit our class from ViewModel with an empty constructor.

class MyViewModel : ViewModel()  {
}

If necessary to remove resources in our implementation, then we should predetermine onCleared() method (this method is called when ViewModel is unavailable for a long period of time and it should be destructed) and remove these resources in this method.

Andrey Derkach
“In addition, so as to avoid memory leak in Android, no need to refer directly to View or Context Activity from ViewModel. Based on this, a question may arise: how can we notify view (Activity/Fragment) of changes in our data? LiveData comes to the rescue.”
class MyViewModel : ViewModel() {
   val isLoadingLiveData = MediatorLiveData<Boolean>()

   fun doSomething() {
       isLoadingLiveData.value = true
   }
}

To get the reference to our ViewModel (Activity/Fragment), we should use ViewModelProviders

override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(layoutId)
       val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
       with(myViewModel) {
           isLoadingLiveData.observe(this@MyActivity, object : Observer<Boolean> {
               override fun onChanged(booleanValue: Boolean?) {
                   if (booleanValue == true) {
                       //todo something
                   } else {
                       //todo something
                   }
               }
           })
           doSomething()
       }
   }
}

You can write that

if (booleanValue == true) {
                       //todo something
                   } else {
                       //todo something
                   }

It is better to replace with

if (booleanValue) {...

But it will be a wrong way since booleanValue variable may become null: 

override fun onChanged(booleanValue: Boolean?)
!

Find out the main features Android P can boast about. Read Top 9 breakthrough Android P 9.0 features every developer should know about

That is why let's just leave it. But we can write the following:

booleanValue?.let {
       	     if (it) {
                       //todo something
                   } else {
                       //todo something
                   }
         }

If in ViewModel you need Context object, you can inherit not ViewModel but AndroidViewModel

class MyViewModel(application: Application) : AndroidViewModel(application) {
}

When you create this model, the provider will pass Application (which is Context) class to model's constructor. getApplication method will help you get this class. 

onSavedInstanceState vs ViewModel

ViewModel and onSavedInstanceState - what is the difference? What type of data should be used with them? 

It may seem that if you have ViewModel that is functioning until Activity is open, you may ignore onSavedInstanceState. But it is a mistake. 

See how we create software at Cleveroad, this video will show you more about our development model: 

Development Process at Cleveroad: How We Create Software

Let's take Activity as an example. Activity can show you the list of specific data and search using them. The user opens Activity and starts searching. Activity shows results based on this search. User minimizes an app. When he/she will open it again, he expects to see everything in the same condition as it was before. 

But imagine that there is not enough memory and a minimized app is closed. When a user will launch it again, Activity will not have any information about search and it will simply show all the data. ViewModel will not be a solution in this case because the model will be killed with an app. But as for onSavedInstanceState, it will be implemented. We can save a search query and get it from savedInstanceState object next time upon the launch and perform the searching. As a result, a user will see the same screen that was available when the app has been minimized. 

Let's summarize. 

ViewModel. It is very convenient to store all data here when you need to form screen. Data will be active when a screen is rotated, but it will be deactivated when the app will be killed by the system. 

onSavedInstanceState. It is used for storing data minimum that is required for restoring screen condition and data in ViewModel data after emergency Activity shutdown by a system. It can be a search query, ID etc. 

It is probably the only weak side of ViewModel: we cannot take ViewModel as a replacement of onSaveInstanceState, and it is still necessary to predetermine onSaveInstanceState method. 

override fun onSaveInstanceState(outState: Bundle?) {
   super.onSaveInstanceState(outState)
}

On the whole, ViewModel component can be described as a singleton with ViewModel classes collection which won't be destroyed while an active copy of Activity is available, and it will remove resources when Activity will be shut down. 

!

Discover new ML toolkit for Firebase. Read ML kit for Firebase: an easy-to-use tool for machine learning 

We hope that this manual was really helpful for you. As you can see, Android Jetpack library can become your good and reliable assistant in app development. Mind to subscribe to our blog where you can find other useful articles, and contact us if you have any questions or ideas! 

Rate this article!

An image An image
Bad!
An image An image
Strange!
An image An image
Boring!
An image An image
Good!
An image An image
Love it!
(305 ratings, average: 4.82 out of 5)
Latest articles
Back to top
As s part of our team, be ready for:
An image
Competitive Base Salary
An image
Comprehensive Benefits
An image
Great Work Environment
An image
Drug Free Workplace
Tell us more about yourself