Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Concurrency in Kotlin
Learning Concurrency in Kotlin

Learning Concurrency in Kotlin: Build highly efficient and scalable applications

Arrow left icon
Profile Icon Castiblanco Torres
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
Paperback Jul 2018 266 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Castiblanco Torres
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
Paperback Jul 2018 266 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Concurrency in Kotlin

Coroutines in Action

It's time to start coding. In this chapter, we will go through the process of enabling support for coroutines in an Android project using Android Studio, and we will use coroutines to solve a common scenario for mobile apps: calling a REST service and displaying some of the response without blocking the UI thread.

Topics that will be covered in this chapter include:

  • Android Studio configuration for Kotlin and projects using coroutines
  • Android's UI thread
  • REST calls in a background thread using coroutines
  • Coroutine builders async() and launch()
  • Introduction to coroutine dispatchers

Downloading and installing Android Studio

The first step for this chapter is to install Android Studio. For this, you can head to https://developer.android.com/studio/index.html and download the installer for your platform.

Kotlin support was added to Android Studio in version 3.0. If you already have Android Studio installed, please check that the version is at least 3.0. It's recommended that you update to the newest stable version of Android Studio if you have an earlier version.
Downloading Android Studio from the official web page

Once you have finished the download, follow the steps on the official guide at https://developer.android.com/studio/install.html to complete the installation. By default, the instructions are going to be according to the operating system detected by the web page; if you wish to see the instructions for a different OS, please select the relevant...

Creating a Kotlin project

When you first open Android Studio, you will be presented with a wizard. To start, select Start a new Android Studio project,as shown in the following screenshot:

Android Studio wizard

Now you will be asked to define the properties of the project. Please make sure that the Include Kotlin support option is enabled:

Setting the properties of a new Android project with Kotlin support

The next step is to select the Android version that you are targeting. The default options are good for this step:

Selecting the target SDKs

Then, select the option to have just an empty activity, and leave its configuration as default:

Selecting an empty activity

Now you will be prompted to select the name for the class and the layout of the activity. Please write MainActivity as the name of the activity, while setting activity_main as the name of the layout:

Configuring...

Adding support for coroutines

Now that the project has been created, it's time to add coroutines support. To do this, open the Project section and double-click in build.gradle for the project. It is located inside the Gradle Scripts section:

The correct build.gradle file says Project: RssReader inside parenthesis

Inside this document, you will add a new variable to centralize the coroutines version. In a new line below ext.kotlin.version, add ext.coroutines_version, as shown here, for example:

buildscript {
ext.kotlin_version = '1.2.50'
ext.coroutines_version = '0.23.3'
...
}
Every time you modify the build.gradle files, Android Studio will ask for the configuration to be synchronized again. Until the synchronization is made, the changes will not be applied.

Now you need to add the dependencies for coroutines. Append the dependency configuration in...

Android's UI thread

As mentioned in the first chapter, Android applications have a thread that is dedicated to updating the UI and also to listening to user interactions and processing the events generated by the user – like the user clicking on a menu.

Let's review the basics of Android's UI thread to guarantee that we separate the work between the UI and background threads in the best way possible.

CalledFromWrongThreadException

Android will throw a CalledFromWrongThreadException whenever a thread that didn't create a view hierarchy tries to update its views. In practical terms, this exception will happen whenever a thread other than the UI thread updates a view. This is because the UI thread is...

Creating a thread

Kotlin has simplified thread creation so that it's a straightforward process and can be done easily. For now, creating a single thread will be enough, but in future chapters we will also create thread pools in order to run both CPU-bound and I/O-bound operations efficiently.

CoroutineDispatcher

It's important to understand that in Kotlin, while you can create threads and thread pools easily, you don't access or control them directly. What you do is create a CoroutineDispatcher, which is basically an orchestrator that distributes coroutines among threads based on availability, load, and configuration.

In our current case, for example, we will create a CoroutineDispatcher that has only one thread...

Adding networking permissions

Android requires applications to explicitly request permissions in order to access many features. This is done in order to present the user with an option to deny specific permissions, and prevent applications from doing something different from what the user expects.

Since we will be doing network requests, we will need to add the internet permission to the manifest of the application. Let's locate the AndroidManifest.xml file in the app/src/main directory, and edit it:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="co.starcarr.rssreader">
<uses-permission android:name="android.permission.INTERNET" />
<application
...
</manifest>
The name Internet is not accurate. This permission is needed in order to do any network request regardless of it actually reaching the...

Creating a coroutine to call a service

Now it's a good time to add a call to a service. To start with something simple, we will use Java's DocumentBuilder to call an RSS feed for us. First, we will add a variable to hold the DocumentBuilderFactory below where we put the dispatcher:

private val dispatcher = newSingleThreadContext(name = "ServiceCall")
private val factory = DocumentBuilderFactory.newInstance()

The second step is to create a function that will do the actual call:

private fun fetchRssHeadlines(): List<String> {
val builder = factory.newDocumentBuilder()
val xml = builder.parse("https://www.npr.org/rss/rss.php?id=1001")
return emptyList()
}

Notice how the function is, for now, returning an empty list of strings after calling the feed. The idea is to implement this function so that it returns the headlines of the given feed. But...

Adding UI elements

Now we can start adding some UI elements to do some testing. First, let's update the layout of MainActivity, which is located in res/layout/activity_main.xml. For now, just adding a ProgressBar will do, so let's replace the contents of the ConstraintLayout so that a ProgressBar is located in the middle of the screen:

<android.support.constraint.ConstraintLayout ...>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
&lt...

Displaying the amount of news that were processed

Let's put a TextView in our layout and display the amount of news that were processed from the feed. Notice that the TextView will be located below the progress bar because of the property app:layout_constraintBottom_toBottomOf:

<android.support.constraint.ConstraintLayout ...>
<ProgressBar ...>
<TextView
android:id="@+id/newsCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@id/progressBar"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

In order to display the amount of news, we will obtain...

Using a UI dispatcher

In the same way that we used a CoroutineDispatcher to run a thread in the background, we can now use one to preform operations in the main thread.

Platform-specific UI libraries

Given that there are many types of GUI applications for the JVM, Kotlin has separated some platform-specific coroutine functionality into libraries.

  • kotlinx-coroutines-android
  • kotlinx-coroutines-javafx
  • kotlinx-coroutines-swing

Notice that all these platforms have the same UI model that we talked about before, in which only the UI thread can create and update the views. So, these tiny libraries are simply a CoroutineDispatcher that is implemented to confine coroutines to the UI thread.

The Android library also adds support for...

Creating an asynchronous function to hold the request... or not

Currently, a big part of our code to request and display the number of news is inside the onCreate() function. This is less than optimal, not only because it's mixed with the creation of the activity, but also because it prevents reusing this code. For example, if there were to be a refresh button, we would need to reuse all the code of the coroutine.

When considering the separation of this coroutine into its own function, there are many possible approaches. Here, we will cover the most common ones.

A synchronous function wrapped in an asynchronous caller

The first approach is quite simple. We can create a loadNews() function that directly invokes fetchRssHeadlines...

Summary

This chapter covered many interesting topics of practical concurrency in Kotlin. Let's do a recap of the key topics.

  • Android applications will throw NetworkOnMainThreadException if a network request is done on the UI thread.
  • Android applications can only update the UI on the UI thread, and trying to do it from a different thread will produce a CalledFromWrongThreadException.
  • Network requests have to be done in a background thread. The information has to be sent to the UI thread for the views to be updated.
  • A CoroutineDispatcher can be used to enforce a coroutine to run in a specific thread, or group of threads.
  • One or many coroutines can be run in a thread by using launch or async.
  • launch should be used in fire-and-forget scenarios, meaning cases where we aren't expecting the coroutine to return something.
  • async should be used when the coroutine will produce...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand Kotlin’s unique approach to multithreading
  • Learn how to write concurrent non-blocking code with the help of practical examples
  • Improve the overall execution speed in multiprocessor and multicore systems

Description

Kotlin is a modern and statically typed programming language with support for concurrency. Complete with detailed explanations of essential concepts, practical examples and self-assessment questions, Learning Concurrency in Kotlin addresses the unique challenges in design and implementation of concurrent code. This practical guide will help you to build distributed and scalable applications using Kotlin. Beginning with an introduction to Kotlin's coroutines, you’ll learn how to write concurrent code and understand the fundamental concepts needed to write multithreaded software in Kotlin. You'll explore how to communicate between and synchronize your threads and coroutines to write collaborative asynchronous applications. You'll also learn how to handle errors and exceptions, as well as how to work with a multicore processor to run several programs in parallel. In addition to this, you’ll delve into how coroutines work with each other. Finally, you’ll be able to build an Android application such as an RSS reader by putting your knowledge into practice. By the end of this book, you’ll have learned techniques and skills to write optimized code and multithread applications.

Who is this book for?

If you’re a Kotlin or Android developer interested in learning how to write concurrent code to enhance the performance of your applications, then this is the book for you. Basic programming knowledge of Java or Kotlin will help you understand the concepts covered in this book.

What you will learn

  • Build secure applications by testing your concurrent code
  • Implement sequential and asynchronous suspending functions
  • Create suspending data sources that can be resumed on demand
  • Explore best practices for error handling
  • Use channels to communicate between coroutines
  • Discover how coroutines help to build parallel applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 30, 2018
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781788627160
Vendor :
JetBrains
Category :
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 30, 2018
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781788627160
Vendor :
JetBrains
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Functional Kotlin
€41.99
Learning Concurrency in Kotlin
€36.99
Hands-On Design Patterns with Kotlin
€36.99
Total 115.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Hello, Concurrent World! Chevron down icon Chevron up icon
Coroutines in Action Chevron down icon Chevron up icon
Life Cycle and Error Handling Chevron down icon Chevron up icon
Suspending Functions and the Coroutine Context Chevron down icon Chevron up icon
Iterators, Sequences, and Producers Chevron down icon Chevron up icon
Channels - Share Memory by Communicating Chevron down icon Chevron up icon
Thread Confinement, Actors, and Mutexes Chevron down icon Chevron up icon
Testing and Debugging Concurrent Code Chevron down icon Chevron up icon
The Internals of Concurrency in Kotlin Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(6 Ratings)
5 star 33.3%
4 star 33.3%
3 star 33.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Cliente Amazon Sep 07, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book, very much comprehensive! It covers a lot of topics and it is really simple to understand. Highly recommended!
Amazon Verified review Amazon
Ahmed Shakil Sep 08, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Honestly I was not expecting this book to explain Coroutines in such an easy and simple way! Author is very experienced in Coroutines and knows how to transfer that knowledge through a book.I request the author to please update the book with new language features and final version of Coroutines release.
Amazon Verified review Amazon
SG May 23, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I really enjoyed reading this book. Unlike many other books on programming languages, this book is NOT a replica or reworded form of the official documentation. The author has really tried to take it a step further to break down complicate concepts an terminology into small chunks which can be absorbed easily. The last chapter on the internals is very helpful in understanding that coroutines are not just magic. They are based on the foundations of classical programming patterns like callbacks, but on steroids.There is however one part of the book which left me unsatisfied and actually confused at the very least. The chapters on Sequence Generators, Iterators and Channels have a lot of terminology or wording which overlaps. So I found it really hard to understand the nuances between them. For example, the chapter on iterators opens with the statement that so far we have learned about suspending functions which suspend while waiting for other operations to complete. So now lets take a look at a different kind of suspending functions for example sequence generators. However, the next chapter on Producers opens with a statement that because iterators and generators only suspend between invocations and not during executions, it is serious limitation and Producers solve this problem. So its like going back to the regular old suspending functions. So it is unclear why iterators were introduced in the book before producers even though the Producers follow the previous chapters more closely. Moreover, since Producers are based on Channels and there is a dedicated chapter for channels in the book, I felt that Channels should have been introduced before talking about Producers. In short, these 2-3 chapters were a mess and took me a couple of a readings to understand the nuances.
Amazon Verified review Amazon
Andrew E. Olson Aug 29, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The coverage is pretty in depth and addressing the relevancy of Kotlin on both Android AND desktop/server is a good approach for breadth. That said, since this was written, Kotlin has moved on so that coroutines have since stabilized which puts the project setup instructions out of date and much of the code out of date. And as of Kotlin 1.3, coroutines have been declared a stable API making a potential new edition of this not only up-to-date, but LASTINGLY. Furthermore, Kotlin-native is now a thing and coverage on concurrency there to compliment the android/desktop breadth would take it another step along with some mention of how coroutines apply to the JavaScript target. So, in short, this is a wonderful book, but it is stuck in yesterday for the time being. And the subject is exploding with relevancy as of the new stability in 1.3 so I would be excited for a new edition. (as a note, I gave the android project with an OLD coroutines version a stab so that I could use the supplied code verbatim, hoping gradle could be coerced to work with the very old kotlin compiler + kotlinx libraries. Well, Android Studio flat out refused ancient Kotlin which is understandable since an IDE front-end must know how to parse a language, but command line gradle also wouldn't cooperate and a modest attempt to use old gradle versions also stumped me with tripwires. I hesitate to flatten a box to go old ubuntu + old android studio because it'll just be more work to learn now irrelevant info. Book really needs a 1.3 bump.
Amazon Verified review Amazon
Dimitri K May 30, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Lots of buzzwords like "blocking" but no clear explanation of principles. Examples for Android, have many unnecessary details, but no organization. Messy, verbose book, with lots of marketing buzzwords, but poor on content. I only give it 3 stars because there is no good one, at least I could not find, and official spec is also very poor.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.