Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Marcin Moskała

Rating 4.0 AI initial rating

Kotlin coroutines have revolutionized JVM development, especially on Android and the backend, as they let us easily implement efficient and reliable multithreading. Their cutting-edge design and features are ideally suited to modern use cases. In this book, we will explore how Kotlin coroutines work and how we can use them to improve our code. This is a practical book. It shows everything by examples and focuses on real-life use cases. As this technology is already widely used on Android and backend applications, we will see how we can use it there and what the best practices are.

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
【One-Line Pitch】 A practical, example-driven guide to Kotlin coroutines that explains how suspension actually works under the hood and then shows how to apply scopes, dispatchers, cancellation, and flows in real Android and backend code. Best for Kotlin developers who already write coroutines and want to stop guessing about the runtime. 【Book Arc】 - **Opening (~0%–10%)**: Frames the problem coroutines solve — callback hell, blocked threads, and hard-to-cancel async code — then introduces suspension and resumption through the "save point" analogy and the `Continuation` object. - **Early (~10%–25%)**: Peels back the compiler transformation: how suspending functions become state machines with labels and captured locals, and how `suspendCoroutine`/`suspendCancellableCoroutine` bridge callback APIs. - **Early (~19%–32%)**: Moves into the `kotlinx.coroutines` library — `launch`, `async`/`Deferred`, `runBlocking`, `coroutineScope`, context inheritance, `Job` states, and the basics of cancellation. - **Middle (~32%–48%)**: Deepens structured concurrency: exception propagation, `supervisorScope` versus `coroutineScope`, dispatchers and `limitedParallelism`, `Dispatchers.Main.immediate`, continuation interception, and Android scope patterns (`ViewModel`, `SupervisorJob`). - **Middle (~48%–55%)**: Covers shared mutable state and synchronization primitives such as `Mutex` and `withLock`, plus testing suspending logic with `runBlocking` and fakes. - **Late/Ending (beyond ~55%)**: The excerpts do not cover the later chapters in detail; based on the book's structure, expect Flow, channels, and advanced production patterns, but this guide cannot summarize them. 【Key Takeaways】 - **Suspension is a save point, not a blocked thread** (Opening): A suspended coroutine returns a `Continuation` and consumes no thread; it can resume later, possibly on another thread. This is the conceptual key to everything else. - **The compiler turns `suspend` functions into state machines** (Early): Labels track the resume point, and locals become fields on a continuation object. Understanding this demystifies "magic" suspension and explains why suspending functions can only be called from coroutines. - **Bridge callback APIs with `suspendCancellableCoroutine`** (Early): Wrapping a callback (e.g., Retrofit) into a suspending function is a core skill; prefer the cancellable variant so cleanup hooks run on cancellation. - **Structured concurrency is the default, and that is the point** (Early–Middle): Builders inherit parent context and propagate failure upward. `coroutineScope` throws catchable exceptions, while `supervisorScope` isolates sibling failures — choose deliberately. - **`supervisorScope` is not interchangeable with `withContext(SupervisorJob())`** (Middle): The book flags this as a common trap; use the scope function when you want independent child tasks. - **Dispatchers are a resource decision** (Middle): `Dispatchers.IO` is a limited view of a shared pool; `limitedParallelism` creates independent limits, and blocking-heavy classes should own their dispatcher. Use `Main.immediate` to avoid redundant re-dispatch. - **Cancellation is cooperative and must be designed in** (Early–Middle): `finally` blocks still run, `invokeOnCancellation` handles cleanup, and `cancelAndJoin` waits for completion. Callback-based code is hard to cancel — another reason to adopt coroutines. - **Shared state needs explicit protection** (Middle): `Mutex.withLock` avoids the deadlock risk of manual `lock`/`unlock`; the excerpts introduce the problem but do not exhaustively cover all primitives. - **Testing suspending code is mostly ordinary testing** (Middle): `runBlocking` plus standard assertions and fakes covers many cases; the author notes his testing style is one preference among many. 【Reading Tips】 - **Deep-read Part 1 (the continuation/state-machine chapters)** even if you only skim later parts — it is the book's differentiator and makes debugging far easier. - **Skim the builder and dispatcher chapters if you already ship coroutine code**, but slow down on `coroutineScope` vs. `supervisorScope` and `SupervisorJob` — these are where production bugs hide. - **Run the snippets**: the book publishes executable sources and uses `println` output with timing annotations, so typing them out pays off. - **Treat the Android `ViewModel` scope patterns as templates**, then adapt the cancellation strategy (`cancelChildren` vs. `cancel`) to your lifecycle. - **Note the book's convention distinction** between `Flow` (type/concept) and a flow (instance); it keeps terminology precise as you move into the Flow chapters. 【Coverage Limits】 This guide is based on stratified excerpts covering roughly the first half of the book (fundamentals through testing); the later Flow, channel, and advanced-practice chapters are not represented here, so treat the Late/Ending arc as indicative only.
Page 9
elling of the “Cancelled” coroutine state. Code conventions Most of the presented snippets are executable code with no import statements. Some chapters of th...
View in text
Excerpt 2
function’s local variables and parameters (as fields), and the reference to the continuation of the function that called this function. One continuation refe...
View in text
Excerpt 3
serAction>) = supervisorScope { actions.forEach { action -> launch { notifyAnalytics(action) } } } Anotherway to stop exception propagation is to use corouti...
View in text
Excerpt 4
Kotlin Coroutines library 177 The problem with shared state Before we start, take a look at the UserDownloader class below. It allows us to fetch a user by i...
View in text
Excerpt 5
nnel) { val offers = offerService .requestOffers(seller.id) offers.forEach { send(it) } } } } } repeat(NUMBER_OF_CONCURRENT_UPDATE_SENDERS) { launch { for (o...
View in text
Excerpt 6
se the catchmethod. This listener receives the exception as an argument and allows you to perform recovering operations. Part 3: Channel and Flow 312 Flow pr...
View in text
Excerpt 7
w<User> = userRepository .observeUserChanges() .filter { it.isSignificantChange } .scan(userRepository.currentUser()) { user, update -> user.with(update) } ....
View in text
Excerpt 8
ges. However, there are also many platform-specific options. I hope you will find this chapter useful when you need to use Kotlin Coroutines from other langu...
View in text
Tags
AI categories
Programming LanguageKotlinBackend
ISBN: 8396395810
Publisher: Leanpub
Publish Year: 2023
Language: English
Pages: 469
File Format: PDF
File Size: 10.4 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Generating text preview…