Learning Concurrency in Kotlin
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

  1. 266 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Learning Concurrency in Kotlin

Build highly efficient and robust applications

Miguel Angel Castiblanco Torres

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Learning Concurrency in Kotlin un PDF/ePUB en línea?
Sí, puedes acceder a Learning Concurrency in Kotlin de Miguel Angel Castiblanco Torres en formato PDF o ePUB, así como a otros libros populares de Ciencia de la computación y Programación en Java. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
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...

Índice