Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
How to Build Android Apps with Kotlin

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

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781838984113
Pages 794 pages
Edition 1st Edition
Languages
Authors (4):
Alex Forrester Alex Forrester
Profile icon Alex Forrester
Eran Boudjnah Eran Boudjnah
Profile icon Eran Boudjnah
Alexandru Dumbravan Alexandru Dumbravan
Profile icon Alexandru Dumbravan
Jomar Tigcal Jomar Tigcal
Profile icon Jomar Tigcal
View More author details

Table of Contents (17) Chapters

Preface
1. Creating Your First App 2. Building User Screen Flows 3. Developing the UI with Fragments 4. Building App Navigation 5. Essential Libraries: Retrofit, Moshi, and Glide 6. RecyclerView 7. Android Permissions and Google Maps 8. Services, WorkManager, and Notifications 9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso 10. Android Architecture Components 11. Persisting Data 12. Dependency Injection with Dagger and Koin 13. RxJava and Coroutines 14. Architecture Patterns 15. Animations and Transitions with CoordinatorLayout and MotionLayout 16. Launching Your App on Google Play

13. RxJava and Coroutines

Overview

This chapter will introduce you to doing background operations and data manipulations with RxJava and coroutines. It covers how to use RxJava to retrieve data from an external API and how to do that with coroutines. You'll also learn how to manipulate and display the data using RxJava operators and LiveData transformations.

By the end of this chapter, you will be able to use RxJava to manage network calls in the background and use RxJava operators to transform data. You will also be able to perform network tasks in the background using Kotlin coroutines and manipulate data with LiveData transformations.

Introduction

You have now learned the basics of Android app development and implemented features such as RecyclerViews, notifications, fetching data from web services, and services. You've also gained skills in the best practices for testing and persisting data. In the previous chapter, you learned about dependency injection. Now, you will be learning about background operations and data manipulation.

Some Android applications work on their own. However, most apps would need a backend server to retrieve or process data. These operations may take a while, depending on the internet connection, device settings, and server specifications. If long-running operations are run in the main UI thread, the application will be blocked until the tasks are completed. The application might become unresponsive and might prompt the user to close it and stop using it.

To avoid this, tasks that can take an indefinite amount of time must be run asynchronously. An asynchronous task means it...

RxJava

RxJava is a Java implementation of Reactive Extensions (Rx), a library for reactive programming. In reactive programming, you have data streams that can be observed. When the value changes, your observers can be notified and react accordingly. For example, let's say clicking on a button is your observable and you have observers listening to it. If the user clicks on that button, your observers can react and do a specific action.

RxJava makes asynchronous data processing and handling errors simpler. Writing it the usual way is tricky and error-prone. If your task involves a chain of asynchronous tasks, it will be more complicated to write and debug. With RxJava, it can be done more easily and you will have less code, which is more readable and maintainable. RxJava also has a wide range of operators that you can use for transforming data into the type or format you need.

RxJava has three main components: observables, observers, and operators. To use RxJava, you will...

Coroutines

Coroutines were added in Kotlin 1.3 for managing background tasks such as making network calls and accessing files or databases. Kotlin coroutines are Google's official recommendation for asynchronous programming on Android. Their Jetpack libraries, such as LifeCycle, WorkManager, and Room, now include support for coroutines.

With coroutines, you can write your code in a sequential way. The long-running task can be made into a suspending function, which when called can pause the thread without blocking it. When the suspending function is done, the current thread will resume execution. This will make your code easier to read and debug.

To mark a function as a suspending function, you can add the suspend keyword to it; for example, if you have a function that calls the getMovies function, which fetches movies from your endpoint and then displays it:

val movies = getMovies()
displayMovies(movies) 

You can make the getMovies() function a suspending function...

Transforming LiveData

Sometimes, the LiveData you pass from the ViewModel to the UI layer needs to be processed first before displaying. For example, you can only select a part of the data or do some processing on it first. In the previous exercise, you filtered the data to only select popular movies from the current year.

To modify LiveData, you can use the Transformations class. It has two functions, Transformations.map and Transformations.switchMap, that you can use.

Transformations.map modifies the value of LiveData into another value. This can be used for tasks like filtering, sorting, or formatting the data. For example, you can transform movieLiveData into string LiveData from the movie's title:

private val movieLiveData: LiveData<Movie>
val movieTitleLiveData : LiveData<String> = 
   Transformations.map(movieLiveData) { it.title }

When movieLiveData changes value, movieTitleLiveData will also change based on the movie's title...

Coroutines Channels and Flows

If your coroutine is fetching a stream of data or you have multiple data sources and you process the data one by one, you can use either Channel or Flow.

Channels allow you to pass data between different coroutines. They are a hot stream of data. It will run and emit values the moment they are called, even when there's no listeners. Flows, meanwhile, are cold asynchronous streams. They only emit values when the values are collected.

To learn more about Channels and Flows, you can go to https://kotlinlang.org.

RxJava versus Coroutines

Both RxJava and coroutines can be used for doing background tasks in Android, such as network calls or database operations.

Which one should you use then? While you can use both in your application, for example, RxJava for one task and coroutines for another, you can also use them together with LiveDataReactiveStreams or kotlinx-coroutines-rx3. This, however, will increase the number of dependencies you use and the size of your application.

So, RxJava or coroutines? The following table shows the differences between the two:

Figure 13.10: Differences between coroutines and RxJava

Let's move on to the next activity.

Activity 13.01: Creating a TV Guide App

A lot of people watch television. Most of the time, though, they are not sure what TV shows are currently on the air. Suppose you wanted to develop an app that can display a list of these shows from The Movie Database API's tv/on_the_air endpoint using Kotlin...

Summary

This chapter focused on doing background operations with RxJava and coroutines. Background operations are used for long-running tasks such as accessing data from the local database or a remote server.

You started with the basics of RxJava: observables, observers, and operators. Observables are the data sources that provide data. The observers listen to observables; when an observable emits data, observers can react accordingly. Operators allow you to modify data from an observable to the data you need before it can be passed to the observers.

Next, you learned how to make RxJava calls asynchronous with schedulers. Schedulers allow you to set the thread through which the required action will be done. The subscribeOn function is used for setting which thread your observable will run on, and the observeOn function allows you to set where the next operators will be executed. You then fetched data from an external API with RxJava and used RxJava operators to filter, sort...

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 2021 Publisher: Packt ISBN-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.
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}