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

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781788626729
Vendor :
JetBrains
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 30, 2018
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781788626729
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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.