Learning Concurrency in Kotlin
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Partager le livre
  1. 266 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Learning Concurrency in Kotlin est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Learning Concurrency in Kotlin par Miguel Angel Castiblanco Torres en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Ciencia de la computaciĂłn et ProgramaciĂłn en Java. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788626729

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...

Table des matiĂšres