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)

Suspending functions

Throughout the book, we have written many suspending algorithms, but most of the time it has been done using coroutine builders such as launch(), async(), and runBlocking(). When calling a coroutine builder, the code that we pass to it is a suspending lambda. Now it's time to take a detailed look at how to write suspending code that exists as a function instead:

suspend fun greetDelayed(delayMillis: Int) {
delay(delayMillis)
println("Hello, World!")
}

To create a suspending function, you only need to add the modifier suspend to its signature. Notice that suspending functions can call other suspending functions such as delay() directly – no need to wrap inside a coroutine builder– making our code clean and easy to read.

Nevertheless, if we try calling this function outside of a coroutine it will not work. Consider this example...