Book Image

Learning Concurrency in Kotlin

By : Miguel Angel Castiblanco Torres
Book Image

Learning Concurrency in Kotlin

By: Miguel Angel Castiblanco Torres

Overview of this book

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.
Table of Contents (11 chapters)

Suspendable sequences and iterators

So far, we have discussed and implemented suspending functions in one way: as functions that suspend while waiting for the execution of one or more computations to happen. A simple representation of this is as follows:

In this example, getProfile starts its execution and, soon after, it suspends to wait for fetchProfile to execute. Once the response has been processed, getProfile suspends once more, this time to call calculateAge. When calculateAge finishes, the execution of getProfile continues until completion.

In this chapter, we will cover a different scenario: writing functions that are suspended between executions. For example, we can have a repository that is suspended until the next page is required:

In the previous example, the next() function will yield the first element from the data source, and will suspend immediately after returning...