22,79 €
Coroutines and flows are the new recommended way for developers to carry out asynchronous programming in Android using simple, modern, and testable code. This book will teach you how coroutines and flows work and how to use them in building Android applications, along with helping you to develop modern Android applications with asynchronous programming using real data.
The book begins by showing you how to create and handle Kotlin coroutines on Android. You’ll explore asynchronous programming in Kotlin, and understand how to test Kotlin coroutines. Next, you'll learn about Kotlin flows on Android, and have a closer look at using Kotlin flows by getting to grips with handling flow cancellations and exceptions and testing the flows.
By the end of this book, you'll have the skills you need to build high-quality and maintainable Android applications using coroutines and flows.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 154
Veröffentlichungsjahr: 2022
Learn how to use Kotlin coroutines and the flow API to handle data streams asynchronously in your Android app
Jomar Tigcal
BIRMINGHAM—MUMBAI
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Nitin Nainani
Senior Editor: Aamir Ahmed
Content Development Editor: Rakhi Patel
Technical Editor: Joseph Aloocaran
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Sinhayna Bais
Marketing Coordinator: Teny Thomas
First published: July 2022
Production reference: 1220722
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80181-624-3
www.packt.com
To my loving wife Celine for her support and encouragement, especially during the time I was writing this book.
To my parents for all their sacrifices and for raising me well.
– Jomar Tigcal
I have known Jomar for over a decade. He and I met when I was planting the seeds for the Google Developer Groups in the Philippines. It started as a help group for Filipino developers who wanted to learn how to develop apps using Google technology. It was soon called the Google Technology Users Group, and it was eventually renamed as Google Developer Group (GDG).
Jomar played a key role in the growth and development of this group. I was looking for someone who could help teach the community how to use HTML5. Jomar was then very shy, but I saw the spark in his eyes whenever new technology was introduced. After much convincing, Jomar agreed to conduct the training session.
We were really surprised by the number of attendees who joined the session. We even had more attendees who joined online (streamed with spotty internet through my tiny netbook). Jomar was obviously very nervous, but when he started getting into tech, I saw him blossom into the well-admired developer he is today.. Soon enough, he was conducting similar sessions during GDG events in Mountain View.
Jomar, with the rest of the GDG team, carried the torch for many years. He developed several useful applications like Sweldong Pinoy, Budget Pinoy, Thirteenth Month, Boto Ko, PHostpaid, Pinoy Jokes, and GDG apps (GDG Watchface and GDG Philippines). He continued to teach and share his knowledge with developers across the country. This book, where you will learn how to build high-quality and maintainable Android applications using Coroutines and Flows, did not come as a surprise.
Jomar continues to inspire and demonstrate to other developers that anything is possible if you put your mind to it. I’m no longer guilty of forcing Jomar to host that first HTML5 training. It is his destiny to help, encourage, and inspire other developers to learn and create more useful applications.
Aileen Apolo-de Jesus
Former Senior Program Manager, Google
Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He has worked on various stages of app development for both small startups and 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, BC, Canada with his wife, Celine.
Shreyas Patil is a Google Developers Expert for Android and works as an Android Developer at Paytm Insider. He is a self-taught developer and has experience in developing Android and web frontend and backend applications. He has several of his own applications published on the Google Play Store. He loves building products and apps and developing useful libraries that help everyone. He’s also an organizer of the community of Kotlin Mumbai. He spends a lot of his development time contributing to open source projects, most of which he started by himself and can be found on his GitHub profile. He loves contributing to the community by writing blogs and articles and making open source projects that can help fellow developers to learn new things.
In this part, we will introduce the concept of asynchronous programming and discuss the new and recommended way to do it with Coroutines. We’ll learn how to create coroutines, handle cancelations and exceptions, and test them.
This section comprises the following chapters:
Chapter 1, Introduction to Asynchronous Programming in AndroidChapter 2, Understanding Kotlin CoroutinesChapter 3, Handling Coroutine Cancelations and ExceptionsChapter 4, Testing Kotlin CoroutinesThere are Android applications that work on their own. But most apps retrieve data from or send data to a local database or a backend server. Examples of these include fetching posts from a social network, saving your favorites from a list, uploading an image, or updating your profile information. These tasks and other resource-intensive computations may happen instantly or take a while to finish. Factors such as internet connection, device specifications, and server settings affect how long these operations take.
Long-running operations must not be performed on the main UI thread as the application will be blocked until they are completed. The application might become unresponsive to the users. Users may not be aware of what’s happening, and this might prompt them to close the app and reopen it (canceling the original task or doing it again). The app can also suddenly crash. Some users might even stop using your app if this happens frequently.
To prevent this from happening, you need to use asynchronous programming. Tasks that can take an indefinite amount of time must be done asynchronously. They must run in the background, parallel to other tasks. For example, while posting information to your backend server, the app displays the UI, which the users can interact with. When the operation finishes, you can then update the UI or notify the users (with a dialog or a snackbar message).
With this book, you will learn how to simplify asynchronous programming in Android using Kotlin coroutines and flows.
In this chapter, you will first start by revisiting the concept of asynchronous programming. After that, you will look into the various ways it is being done now in Android and how they may no longer be the best way moving forward. Then, you will be introduced to the new, recommended way of performing asynchronous programming in Android: coroutines and flows.
This chapter covers three main topics:
Asynchronous programmingThreads, AsyncTasks, and ExecutorsThe new way to do it – coroutines and flowsBy the end of this chapter, you will have a basic understanding of asynchronous programming, and know how to do it in Android using threads, AsyncTasks, and Executors. Finally, you will discover Kotlin coroutines and flows as these are the recommended ways of doing asynchronous programming in Android.
You will need to download and install the latest version of Android Studio. You can find the latest version at https://developer.android.com/studio. For an optimal learning experience, a computer with the following specifications is recommended: Intel Core i5 or equivalent or higher, 4 GB RAM minimum, and 4 GB available space.
The code examples for this book can be found on GitHub at https: github.com/PacktPublishing/Simplifying-Android-Development-with-Coroutines-and-Flows.
In this section, we will start by looking at asynchronous programming. Asynchronous programming is a programming method that allows work to be done independently of the main application thread.
A normal program will run sequentially. It will perform one task and move to the next task after the previous one has finished. For simple operations, this is fine. However, there are some tasks that might take a long time to finish, such as the following:
Fetching data from or saving data to a databaseGetting, adding, or updating data to a networkProcessing text, images, videos, or other filesComplicated computationsThe app will look frozen and unresponsive to the users while it is performing these tasks. They won’t be able to do anything else in the app until the tasks are finished.
Asynchronous programming solves this problem. You can run a task that may be processed indefinitely on a background thread (in parallel to the main thread) without freezing the app. This will allow the users to still interact with the app or the UI while the original task is running. When the task has finished or if an error was encountered, you can then inform the user using the main thread.
A visual representation of asynchronous programming is shown in the following figure:
Figure 1.1 – Asynchronous programming
Task 1 and Task 2 are running on the main thread. Task 2 starts Task 3 on the background thread. While Task 3 is running, the main thread can continue to perform other tasks, such as Task 4. After Task 3 is done, it will return to the main thread.
Asynchronous programming is an important skill for developers to have, especially for mobile app development. Mobile devices have limited capabilities and not all locations have a stable network connection.
In Android, if you run a task on the main thread and it takes too long, the app can become unresponsive or look frozen. The app can also crash unexpectedly. You will likely get an Application Not Responding (ANR) error, as shown in the following screenshot:
Figure 1.2 – An ANR dialog
Starting with Android 3.0 (Honeycomb), running a network operation on the main thread will cause android.os.NetworkOnMainThreadException, which will crash your app.
ANR dialogs and crashes can annoy your users. If they happen all the time, they might stop using your app altogether and choose another app. To prevent them in your app, you must run tasks that can take a long period of time on the background thread.
In this section, you revisited the concept of asynchronous programming and how you can use it to run long-running tasks without freezing the app. You will explore various approaches for using asynchronous programming in Android in the next section.
