Chapter 1: Introduction to Asynchronous Programming in Android
There 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 programming
- Threads, AsyncTasks, and
Executors
- The new way to do it – coroutines and flows
By 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.