Learning Concurrency in Kotlin
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Buch teilen
  1. 266 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

Take advantage of Kotlin's concurrency primitives to write efficient multithreaded applications

Key Features

  • Learn Kotlin's unique approach to multithreading
  • Work through practical examples that will help you write concurrent non-blocking code
  • Improve the overall execution speed in multiprocessor and multicore systems

Book Description

The primary requirements of modern-day applications are scalability, speed, and making the most use of hardware. Kotlin meets these requirements with its immense support for concurrency. Many concurrent primitives of Kotlin, such as channels and suspending functions, are designed to be non-blocking and efficient. This allows for new approaches to concurrency and creates unique challenges for the design and implementation of concurrent code. Learning Concurrency in Kotlin addresses those challenges with real-life examples and exercises that take advantage of Kotlin's primitives. Beginning with an introduction to Kotlin's coroutines, you will learn how to write concurrent code and understand the fundamental concepts needed to be able to write multithreaded software in Kotlin. You'll explore how to communicate between and synchronize your threads and coroutines to write asynchronous applications that are collaborative. You'll also learn how to handle errors and exceptions, as well as how to leverage multi-core processing. In addition to this, you'll delve into how coroutines work internally, allowing you to see the bigger picture. Throughout the book you'll build an Android application – an RSS reader – designed and implemented according to the different topics covered in the book

What you will learn

  • Understand Kotlin's approach to concurrency
  • Implement sequential and asynchronous suspending functions
  • Create suspending data sources that are resumed on demand
  • Explore the best practices for error handling
  • Use channels to communicate between coroutines
  • Uncover how coroutines work under the hood

Who this book is for

If you're a Kotlin or Android developer interested in learning how to program concurrently to enhance the performance of your applications, this is the book for you.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Learning Concurrency in Kotlin als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Learning Concurrency in Kotlin von Miguel Angel Castiblanco Torres im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Ciencia de la computación & Programación en Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Suspending Functions and the Coroutine Context

So far, we have limited ourselves to writing suspending code using coroutine builders such as launch and async, but Kotlin offers more ways to write it. In this chapter, we will start by updating our RSS reader to actually display the articles that it retrieved, then we will learn about suspending functions and compare them with the async functions that we have been using so far. Also, we will cover the coroutine context and its use in detail.
Here is a summary of topics that will be covered in this chapter:
  • What a suspending function is
  • How to use suspending functions
  • When to use async functions instead of suspending functions
  • What the coroutine context is
  • Different types of contexts such as dispatcher, exception handlers, and non-cancellables
  • Combining and separating contexts to define the behavior of coroutines

Improving the UI of the RSS Reader

This is a good moment to make our RSS Reader more user friendly. Let's update the application so that it displays the information of the news articles as a list that the user can scroll, and let's display not only the headline of the article but also a summary of it and the feed that it belongs to.

Giving each feed a name

First, let's start by creating a new package, model, so that we can organize our data classes, and let's create a Kotlin model.kt inside it, as shown:
We want to be able to identify a feed not only by its URL but also by a name, so let's now create a data class called Feed inside our new model file. This class will hold pairs of a name and a url for each feed:
package co.starcarr.rssreader.model

data class Feed(
val name: String,
val url: String
)
Now we can update feeds in MainActivity so that its contents are of type Feed. Notice that the last element on the list is an invalid feed.
private val feeds = listOf(
Feed("npr", "https://www.npr.org/rss/rss.php?id=1001"),
Feed("cnn", "http://rss.cnn.com/rss/cnn_topstories.rss"),
Feed("fox", "http://feeds.foxnews.com/foxnews/latest?format=xml"),
Feed("inv", "htt:myNewsFeed")
)
It will be convenient to update the function asyncFetchHeadlines() so that it takes a Feed and uses its URL property to fetch the feed:
private fun asyncFetchHeadlines(feed: Feed,
dispatcher: CoroutineDispatcher) = async(dispatcher) {
val builder = factory.newDocumentBuilder()
val xml = builder.parse(feed.url)
...
}

Fetching more information about the articles from the feed

As mentioned previously, we want to display a convenient set of information about each of the articles: feed, title, and summary. So let's create a data class that will hold that information. We can create it right below Feed:
package co.starcarr.rssreader.model

data class Feed(
val name: String,
val url: String
)
data class Article(
val feed: String,
val title: String,
val summary: String
)
Instead of having the function asyncFetchHeadlines(), which returns only the title, we want the function to now be named asyncFetchArticles() an...

Inhaltsverzeichnis