Learning Concurrency in Kotlin
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Condividi libro
  1. 266 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Learning Concurrency in Kotlin è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Learning Concurrency in Kotlin di Miguel Angel Castiblanco Torres in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Ciencia de la computación e Programación en Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

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

Indice dei contenuti