Reader small image

You're reading from  Kickstart Modern Android Development with Jetpack and Kotlin

Product typeBook
Published inMay 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801811071
Edition1st Edition
Languages
Right arrow
Author (1)
Catalin Ghita
Catalin Ghita
author image
Catalin Ghita

Catalin Ghita is a Udemy Instructor and an Android Engineer proficient in Native Android Development, while also being active in Cross-platform development with React-Native and Flutter. He successfully built, deployed, and maintained huge scalable apps with millions of downloads and active users for industry giants like Burger King, Carrefour or Bankinter. He is designated to architect huge applications into scalable, maintainable and testable form and shapes. As the owner of the Coding Troops blog and Udemy instructor, he wrote articles and taught courses reaching tens of thousands of students, thereby exposing and clarifying concepts and subtleties on hot topics in Android.
Read more about Catalin Ghita

Right arrow

Chapter 4: Handling Async Operations with Coroutines

In this chapter, we're focusing on another library that, although is not in the Jetpack library suite, is essential for writing solid applications: Kotlin coroutines.

Coroutines represent a more convenient way of handling async work and concurrency jobs on Android.

In this chapter, we will study how we can replace callbacks with coroutines in our Restaurants application. In the first section, Introducing Kotlin coroutines, we will gain a better understanding of what coroutines are, how they work, and why we need them in our apps.

In the next section, Exploring the basic elements of coroutines, we will explore the core elements of coroutines, and we will understand how to use them to handle asynchronous work more concisely.

Finally, in the Using coroutines for async work section, we will implement coroutines in our Restaurants application and let them handle the network requests. Additionally, we will add error handling...

Technical requirements

Building Compose-based Android projects with coroutines usually requires your day-to-day tools. However, to follow along with this chapter smoothly, make sure you have the following:

  • The Arctic Fox 2020.3.1 version of Android Studio. You can also use a newer Android Studio version or even Canary builds but note that IDE interface and other generated code files might differ from the ones used throughout this book.
  • Kotlin 1.6.10, or a newer plugin, installed in Android Studio
  • The Restaurants app code from the previous chapter.

The starting point for this chapter is represented by the Restaurants application developed in the previous chapter. If you haven't followed the implementation from the previous chapter, access the starting point for this chapter by navigating to the Chapter_03 directory of the repository and importing the Android project entitled chapter_3_restaurants_app.

To access the solution code for this chapter, navigate...

Introducing Kotlin coroutines

Coroutines are part of the Kotlin API. They introduce a new and easier way of handling async work and concurrency jobs.

Often, with Android, we need to run or execute different tasks behind the scenes. In the meantime, we don't want to block the main thread of the application and get an unresponsive UI.

To mitigate this issue, coroutines allow you to execute async work much easier while providing main-thread safety for your Android apps. You can use the Coroutines API by launching one coroutine, or more, depending on your needs.

In this section, we will cover three essential questions about the Coroutines API that derive from what we stated earlier:

  • What is a coroutine?
  • What are the features and advantages of coroutines?
  • How do coroutines work?

Let's jump in!

What is a coroutine?

A coroutine is a concurrency design pattern for async work. A coroutine represents an instance of suspendable computation.

In...

Exploring the basic elements of coroutines

A very simplistic approach for getting async work done with coroutines could be expressed as follows: first, define the suspended functions and then create coroutines that execute the suspended functions.

Yet, we're not only unsure what suspending functions look like, but we also don't know how to allow coroutines to perform asynchronous work for us.

Let's take things, step by step, and start with the two essential actions that we need to execute async work with coroutines:

  • Creating suspending functions
  • Launching coroutines

All of these terms make little sense now, so let's address this, starting with suspending functions!

Creating suspending functions

The first thing that we need in order to work with coroutines is to define a suspending function where the blocking task resides.

A suspending function is a special function that can be paused (suspended) and resumed at some later point in...

Using coroutines for async work

The first thing that we have to do is identify the async/heavy work that we have done in our Restaurants application.

Without looking at the code, we know that our app retrieves a list of restaurants from the server. It does that by initiating a network request with Retrofit and then waits for a response. This action qualifies as an async job because we don't want to block the main (UI) thread while the app waits for the network response to arrive.

If we check out the RestaurantsViewModel class, we can identify that the getRestaurants() method is the one place in our application where heavy blocking work is happening:

private fun getRestaurants() {
    restaurantsCall = restInterface.getRestaurants()
    restaurantsCall.enqueue(object : Callback
        <List<Restaurant>> {
            override...

Summary

In this chapter, we learned how coroutines allow us to write async code in a much clearer and more concise way.

We understood what coroutines are, how they work, and why they are needed in the first place. We unveiled the core elements of coroutines: from suspend functions to CoroutineScope objects, to CoroutineContext objects and Dispatcher objects.

Then, we replaced the callbacks with coroutines in our Restaurants application and noticed how the code is much easier to understand and less nested. Additionally, we learned how to perform error handling with coroutines and integrated some of the best practices when working with coroutines.

In the next chapter, we will add another Compose-based screen to our Restaurants application and learn how to navigate between screens in Compose with yet another Jetpack library.

Further reading

While canceling coroutines might seem simple with the help of the associated Job objects, it's important to note that any cancelation must be cooperative. More specifically, when coroutines perform suspending work based on conditional statements, you must ensure the coroutine is cooperative with respect to canceling.

You can read about this topic, in more detail, in the official documentation: https://kotlinlang.org/docs/cancellation-and-timeouts.html#cancellation-is-cooperative.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Kickstart Modern Android Development with Jetpack and Kotlin
Published in: May 2022Publisher: PacktISBN-13: 9781801811071
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

Author (1)

author image
Catalin Ghita

Catalin Ghita is a Udemy Instructor and an Android Engineer proficient in Native Android Development, while also being active in Cross-platform development with React-Native and Flutter. He successfully built, deployed, and maintained huge scalable apps with millions of downloads and active users for industry giants like Burger King, Carrefour or Bankinter. He is designated to architect huge applications into scalable, maintainable and testable form and shapes. As the owner of the Coding Troops blog and Udemy instructor, he wrote articles and taught courses reaching tens of thousands of students, thereby exposing and clarifying concepts and subtleties on hot topics in Android.
Read more about Catalin Ghita