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

14. Architecture Patterns

Overview

This chapter will introduce you to architectural patterns you can use for your Android projects. It covers using the MVVM (Model-View-ViewModel) pattern, adding ViewModels, and using data binding. You will also learn about using the Repository pattern for caching data and WorkManager for scheduling data retrieval and storage.

By the end of the chapter, you will be able to structure your Android project using MVVM and data binding. You will also be able to use the Repository pattern with Room library to cache data and WorkManager to fetch and save data at a scheduled interval.

Introduction

In the previous chapter, you learned about using RxJava and coroutines for doing background operations and data manipulation. Now, you will learn about architectural patterns so you can improve your application.

When developing an Android application, you might tend to write most of the code (including business logic) in activities or fragments. This would make your project hard to test and maintain later. As your project grows and becomes more complex, the difficulty will increase too. You can improve your projects with architectural patterns.

Architectural patterns are general solutions for designing and developing parts of applications, especially for large apps. There are architectural patterns you can use to structure your project into different layers (the presentation layer, the user interface (UI) layer, and the data layer) or functions (observer/observable). With architectural patterns, you can organize your code in a way that makes it easier for you...

MVVM

MVVM allows you to separate the UI and business logic. When you need to redesign the UI or update the Model/business logic, you only need to touch the relevant component without affecting the other components of your app. This will make it easier for you to add new features and test your existing code. MVVM is also useful in creating huge applications that use a lot of data and views.

With the MVVM architectural pattern, your application will be grouped into three components:

  • Model: Represents the data layer
  • View: The UI that displays the data
  • ViewModel: Fetches data from the Model and provides it to the View

The MVVM architectural pattern can be understood better through the following diagram:

Figure 14.1: The MVVM architectural pattern

The Model contains the data and the business logic of the application. The activities, fragments, and layouts that your users see and interact are the Views in MVVM. Views only deal...

Data Binding

Data binding links the views in your layout to data from a source such as a ViewModel. Instead of adding code to find the views in the layout file and updating them when the value from the ViewModel changes, data binding can handle that for you automatically.

To use data binding in your Android project, you should add the following in the android block of the app/build.gradle file:

buildFeatures {
    dataBinding true
}

In the layout file, you must wrap the root element with a layout tag. Inside the layout tag, you need to define the data element for the data to be bound to this layout file:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="movie" type="com.example.model.Movie"/>
    </data>
    <ConstraintLayout ... />
</layout...

Retrofit and Moshi

When connecting to your remote network, you can use Retrofit. Retrofit is an HTTP client that makes it easy to implement creating requests and retrieving responses from your backend server.

You can add Retrofit to your project by adding the following code in your app/build.gradle file dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

You can then convert the JSON response from Retrofit by using Moshi, a library for parsing JSON into Java objects. For example, you can convert the JSON string response from getting the list of movies into a ListofMovie object for display and storage in your app.

You can add the Moshi Converter to your project by adding the following code to your app/build.gradle file dependencies:

implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'

In your Retrofit builder code, you can call addConverterFactory and pass MoshiConverterFactory:

Retrofit.Builder()
   ...

The Repository Pattern

Instead of the ViewModel directly calling the services for getting and storing data, it should delegate that task to another component, such as a repository.

With the Repository pattern, you can move the code in the ViewModel that handles the data layer into a separate class. This reduces the complexity of the ViewModel, making it easier to maintain and test. The repository will manage where the data is fetched and stored, just as if the local database or the network service were used to get or store data:

Figure 14.3: ViewModel with the Repository pattern

In your ViewModel, you can add a property for the repository:

class MovieViewModel(val repository: MovieRepository): ViewModel() {
... 
}

The ViewModel will get the movies from the repository, or it can listen to them. It will not know where you actually got the list from.

You can create a repository interface that connects to a data source, such as in the following example...

WorkManager

WorkManager is a Jetpack library for background operations that can be delayed and can run based on the constraints you set. It is ideal for doing something that must be run but can be done later or at regular intervals, regardless of whether the app is running or not.

You can use WorkManager to run tasks such as fetching the data from the network and storing it in your database at scheduled intervals. WorkManager will run the task even if the app has been closed or if the device restarts. This will keep your database up to date with your backend.

You can add WorkManager to your project by adding the following code to your app/build.gradle file dependencies:

implementation 'androidx.work:work-runtime:2.4.0'

WorkManager can call the repository to fetch and store data from either the local database or the network server.

Let's try adding WorkManager to an Android project.

Exercise 14.03: Adding WorkManager to an Android Project

In the previous...

Summary

This chapter focused on architectural patterns for Android. You started with the MVVM architectural pattern. You learned its three components: the Model, the View, and the ViewModel. You also used data binding to link the View with the ViewModel.

Next, you learned about how the Repository pattern can be used to cache data. Then, you learned about WorkManager and how you can schedule tasks such as retrieving data from the network and saving that data to the database to update your local data.

In the next chapter, you will be learning how to improve the look and design of your apps with animations. You will add animations and transitions to your apps with CoordinatorLayout and MotionLayout.

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