Reader small image

You're reading from  How to Build Android Apps with Kotlin

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984113
Edition1st Edition
Languages
Right arrow
Authors (4):
Alex Forrester
Alex Forrester
author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

Eran Boudjnah
Eran Boudjnah
author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

Alexandru Dumbravan
Alexandru Dumbravan
author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

Jomar Tigcal
Jomar Tigcal
author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal

View More author details
Right arrow

10. Android Architecture Components

Overview

In this chapter, you will learn about the key components of the Android Jetpack libraries and what benefits they bring to the standard Android framework. You will also learn how to structure your code and give different responsibilities to your classes with the help of Jetpack components. Finally, you'll improve the test coverage of your code.

By the end of this chapter, you'll be able to create applications that handle the life cycles of activities and fragments with ease. You'll also know more about how to persist data on an Android device using Room, as well as how to use ViewModels to separate your logic from your Views.

Introduction

In the previous chapters, you learned how to write unit tests. The question is: what can you unit test? Can you unit test activities and fragments? They are pretty hard to unit test on your machine because of the way they are built. Testing would be easier if you could move the code away from activities and fragments.

Also, consider the situation where you are building an application that supports different orientations, such as landscape and portrait, and supports multiple languages. What tends to happen in these scenarios by default is that when the user rotates the screen, the activities and fragments are recreated for the new display orientation. Now, imagine that happens while your application is in the middle of processing data. You have to keep track of the data you are processing, you have to keep track of what the user was doing to interact with your screens, and you have to avoid causing a context leak.

Note

A context leak occurs when your destroyed...

ViewModel and LiveData

Both ViewModel and LiveData represent specialized implementations of the life cycle mechanisms. They come in handy in situations where you want to keep your data saved when the screen rotates and when you want your data to be displayed only when the Views are available, thus avoiding one of the most common issues developers face – a NullPointerException – when trying to update a View. A good use of this is when you want to display the live score of your favorite team's game and the current minute of the game.

ViewModel

The ViewModel component is responsible for holding and processing data required by the UI. It has the benefit of surviving configuration changes that destroy and recreate fragments and activities, which allows it to retain the data that can then be used to re-populate the UI. It will be eventually destroyed when the activity or fragment will be destroyed without being recreated or when the application process is terminated...

Room

The Room persistence library acts as a wrapper between your application code and the SQLite storage. You can think of SQLite as a database that runs without its own server and saves all the application data in an internal file that's only accessible by your application (if the device is not rooted). Room will sit between the application code and the SQLite Android Framework, and it will handle the necessary Create, Read, Update, and Delete (CRUD) operations while exposing an abstraction that your application can use to define the data and how you want the data to be handled. This abstraction comes in the form of the following objects:

  • Entities: You can specify how you want your data to be stored and the relationships between your data.
  • Data Access Object (DAO): The operations that can be done on your data.
  • Database: You can specify the configurations that your database should have (the name of the database and migration scenarios).

These can be seen...

Customizing Life Cycles

Previously, we discussed LiveData and how it can be observed through a LifecycleOwner. We can use LifecycleOwners to subscribe to a LifecycleObserver so that it will monitor when the state of an owner changes. This is useful in situations where you would want to trigger certain functions when certain life cycle callbacks are invoked; for example, requesting locations, starting/stopping videos, and monitoring connectivity changes from your activity/fragment. We can achieve this with the use of a LifecycleObserver:

class ToastyLifecycleObserver(val onStarted: () -> Unit) :   LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStarted() {
        onStarted.invoke()
    }
}

In the preceding code, we have defined a class that implements the LifecycleObserver interface and defined a method that will be called when the life cycle goes...

Summary

In this chapter, we analyzed the building blocks required to build a maintainable application. We also looked into one of the most common issues that developers come across when using the Android Framework, which is maintaining the states of objects during life cycle changes.

We started by analyzing ViewModels and how they solve the issue of holding data during orientation changes. We added LiveData to ViewModels to show how the two complement each other.

We then moved on to Room to show how we can persist data with minimal effort and without a lot of SQLite boilerplate code. We also explored one-to-many and many-to-many relationships, as well as how to migrate data and break down complex objects into primitives for storage.

After that, we reinvented the Lifecycle wheel in order to show how LifecycleOwners and LifecycleObservers interact.

We also built our first repository, which we will expand upon in the following chapters when other data sources are added into...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021Publisher: PacktISBN-13: 9781838984113
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (4)

author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal