Leanpub Header

Skip to main content

Kotlin Coroutines

Deep Dive

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.

The author is letting you choose the price you pay for this book!

Pick Your Price...
PDF
EPUB
WEB
About

About

About the Book

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.

If you are interested in paperback, you can purchase it here.

Share this book

Installments completed

25 / 25

Price

Pick Your Price...

Minimum price

$19.99

$29.99

You pay

$29.99

Author earns

$23.99
$

All prices are in US $. You can pay in US $ or in your local currency when you check out.

EU customers: prices exclude VAT, which is added during checkout.

...Or Buy With Credits!

Number of credits (Minimum 2)

2
The author will earn $24.00 from your purchase!
You can get credits monthly with a Reader Membership

Author

About the Author

Marcin Moskała

Marcin Moskala is an experienced developer and Kotlin trainer. He is the founder of the kt.academy, Kotlin GDE, an official JetBrains partner for teaching Kotlin, and author of the books Effective Kotlin, Kotlin Coroutines, and Android Development with Kotlin.

Leanpub Podcast

Episode 254

An Interview with Marcin Moskała

Translations

Translations

Languages

Contents

Table of Contents

Introduction

  1. Who is this book for?
  2. The structure of this book
  3. What will be covered?
  4. The Kotlin for Developers series
  5. Conventions
  6. Code conventions
  7. Version
  8. Exercises and solutions
  9. Acknowledgments

Part 1: Understanding Kotlin Coroutines

Why Kotlin Coroutines?

  1. Simplicity
  2. Performance
  3. Cancellation
  4. Synchronization
  5. Testability
  6. Flow
  7. Coroutines are multiplatform
  8. The biggest problem with Kotlin Coroutines
  9. Summary

Sequence builder

  1. Real-life usages
  2. Exercise: Factorial sequence
  3. Exercise: Prime numbers sequence

How does suspension work?

  1. A game analogy
  2. Suspending functions
  3. Your first suspension
  4. What is stored in the continuation?
  5. Delaying a coroutine
  6. Resuming with a value
  7. Resume with an exception
  8. Suspending a coroutine, not a function
  9. Summary
  10. Exercise: Callback function wrappers
  11. Exercise: Continuation storage

Coroutines under the hood

  1. Continuation-passing style
  2. A very simple function
  3. A function with a state
  4. A function resumed with a value
  5. The call stack
  6. Suspending functions in other contexts
  7. The actual code
  8. The performance of suspending functions
  9. Summary
  10. Exercise: What is stored by a continuation?

Coroutines: built-in support vs library

Part 2: Kotlin Coroutines library

Starting coroutines

  1. Asynchronous coroutine builders
  2. Blocking coroutine builders
  3. Structured Concurrency
  4. Coroutine scope functions
  5. Summary
  6. Exercise: UserDetailsRepository
  7. Exercise: BestStudentUseCase
  8. Exercise: CommentService
  9. Exercise: mapAsync

The bigger picture

Coroutine context

  1. CoroutineContext interface
  2. Finding elements in CoroutineContext
  3. Adding contexts
  4. Empty coroutine context
  5. Subtracting elements
  6. Folding context
  7. Coroutine context and builders
  8. Accessing context in a suspending function
  9. Changing context in suspending functions
  10. Creating our own context
  11. Coroutines and thread elements
  12. Summary
  13. Exercise: Understanding context propagation
  14. Exercise: CounterContext

Dispatchers

  1. Default dispatcher
  2. Limiting the default dispatcher
  3. Main dispatcher
  4. IO dispatcher
  5. Dispatcher with a custom limit
  6. Dispatcher with a fixed pool of threads
  7. Dispatcher limited to a single thread
  8. Using virtual threads from Project Loom
  9. Unconfined dispatcher
  10. Immediate main dispatching
  11. Continuation interceptor
  12. Performance of dispatchers when executing different tasks
  13. Summary
  14. Exercise: Using dispatchers
  15. Exercise: DiscNewsRepository
  16. Exercise: Experiments with dispatchers

Job and coroutine lifecycle

  1. Job and relationships
  2. Coroutine lifecycle
  3. Awaiting job completion
  4. The Job factory function
  5. Synchronizing coroutines
  6. Summary

Cancellation

  1. Basic cancellation
  2. The finally block
  3. invokeOnCompletion
  4. Cancellation of children
  5. Cancellation in a coroutine scope
  6. Just one more call
  7. Stopping the unstoppable
  8. CancellationException is special
  9. CancellationException does not propagate to its parent
  10. withTimeout
  11. suspendCancellableCoroutine
  12. Summary
  13. Exercise: Correct mistakes with cancellation

Exception handling

  1. Exceptions and structured concurrency
  2. SupervisorJob
  3. supervisorScope
  4. Exceptions and await call
  5. CoroutineExceptionHandler
  6. Summary

Constructing a coroutine scope

  1. CoroutineScope factory function
  2. Constructing a background scope
  3. Constructing a scope on Android
  4. Summary
  5. Exercise: NotificationSender
  6. Exercise: BaseViewModel

Synchronizing access to mutable state

  1. Using atomic values
  2. Synchronized blocks
  3. Using a dispatcher limited to a single thread
  4. Mutex
  5. Semaphore
  6. Summary
  7. Exercise: CompanyDetailsRepository
  8. Exercise: CancellingRefresher
  9. Exercise: TokenRepository
  10. Exercise: Suspended lazy
  11. Exercise: mapAsync with concurrency limit

Testing Kotlin Coroutines

  1. Testing time dependencies
  2. TestCoroutineScheduler and StandardTestDispatcher
  3. runTest
  4. Background scope
  5. Testing cancellation and context passing
  6. UnconfinedTestDispatcher
  7. Using mocks
  8. Testing functions that change a dispatcher
  9. Testing what happens during function execution
  10. Testing functions that launch new coroutines
  11. Testing classes that need scope in runTest
  12. Replacing the main dispatcher
  13. Testing Android functions that launch coroutines
  14. Setting a test dispatcher with a rule
  15. Summary
  16. Exercise: Test UserDetailsRepository
  17. Exercise: Testing mapAsync
  18. Exercise: Testing the NotificationSender class
  19. Exercise: Testing a View Model

Part 3: Channel and Flow

Channel

  1. Channel types
  2. On buffer overflow
  3. On undelivered element handler
  4. Fan-out
  5. Fan-in
  6. Pipelines
  7. Practical usage
  8. Summary
  9. Exercise: UserRefresher
  10. Exercise: Cafeteria simulation

Select

  1. Selecting deferred values
  2. Selecting from channels
  3. Summary
  4. Exercise: raceOf

Hot and cold data sources

  1. Hot vs cold
  2. Hot channels, cold flow
  3. Summary

Flow introduction

  1. Comparing flow to other ways of representing values
  2. The characteristics of Flow
  3. Flow nomenclature
  4. Real-life use cases
  5. Summary

Understanding Flow

  1. Understanding Flow
  2. How Flow processing works
  3. Flow is synchronous
  4. Flow and shared state
  5. Conclusion

Flow building

  1. Flow from raw values
  2. Converters
  3. Converting a function to a flow
  4. Flow and Reactive Streams
  5. Flow builders
  6. Understanding flow builder
  7. channelFlow
  8. callbackFlow
  9. Summary
  10. Exercise: Flow utils
  11. Exercise: All users flow
  12. Exercise: distinct

Flow lifecycle functions

  1. onEach
  2. onStart
  3. onCompletion
  4. onEmpty
  5. catch
  6. Uncaught exceptions
  7. retry
  8. flowOn
  9. launchIn
  10. Summary
  11. Exercise: TemperatureService
  12. Exercise: NewsViewModel

Flow processing

  1. map
  2. filter
  3. take and drop
  4. How does collection processing work?
  5. merge, zip and combine
  6. fold and scan
  7. flatMapConcat, flatMapMerge and flatMapLatest
  8. Distinct until changed
  9. buffer and conflate
  10. debounce
  11. sample
  12. Terminal operations
  13. Summary
  14. Exercise: ProductService
  15. Exercise: Flow Kata
  16. Exercise: MessageService

SharedFlow and StateFlow

  1. SharedFlow
  2. shareIn
  3. StateFlow
  4. stateIn
  5. Summary
  6. Exercise: Update ProductService
  7. Exercise: Update TemperatureService
  8. Exercise: LocationService
  9. Exercise: PriceService
  10. Exercise: NewsViewModel using stateIn

Testing flow

  1. Transformation functions
  2. Testing infinite flows
  3. Determining how many connections were opened
  4. Testing view models
  5. Summary
  6. Exercise: Flow testing

Part 4: Kotlin Coroutines in practice

Common use cases

  1. Data/Adapters Layer
  2. Domain Layer
  3. Presentation/API/UI layer
  4. Summary

Using coroutines from other languages

  1. Threads on different platforms
  2. Transforming suspending into non-suspending functions
  3. Calling suspending functions from other languages
  4. Flow and Reactive Streams
  5. Summary

Launching coroutines vs. suspending functions

Best practices

The End

Exercise solutions

Contributors

About the Contributors

Vsevolod Tolstopyatov

a team lead of the Kotlin Libraries team. He works at JetBrains and is interested in API design, concurrency, JVM internals, performance tuning and methodologies.

Sean McQuillan

a Developer Advocate at Google. With a decade of experience at Twilio and other San Francisco startups, he is an expert at building apps that scale. Sean is passionate about using great tooling to build high-quality apps quickly. When he is not working on Android, you can find him fiddling on the piano or crocheting hats.

Richard Schielek

an experienced developer and an early adopter of Kotlin and coroutines, using both in production before they became stable. Worked in the European space industry for several years.

Nicola Corti

a Google Developer Expert for Kotlin. He has been working with the language since before version 1.0, and he is the maintainer of several open-source libraries and tools for mobile developers (Detekt, Chucker, AppIntro). He's currently working in the React Native core team at Meta, building one of the most popular cross-platform mobile frameworks. Furthermore, he is an active member of the developer community. His involvement goes from speaking at international conferences to being a member of CFP committees and supporting developer communities across Europe. In his free time, he also loves baking, podcasting, and running.

Jana Jarolimov

an Android developer at Avast. She started her career teaching Java classes at Prague City University, before moving on to mobile development, which inevitably led to Kotlin and her love thereof.

Ilmir Usmanov

a software developer at JetBrains, working on coroutine support in the Kotlin compiler since 2017. Was responsible for stabilization and implementation of the coroutines design. Since then, he has moved to other features, namely inline classes. Currently, his work with coroutines is limited to bug fixing and optimization, since coroutines as a language feature is complete and stable and does not require much attention.

Igor Wojda

a passionate engineer with over a decade of software development experience. He is deeply interested in Android application architecture and the Kotlin language, and he is an active member of the open-source community. Igor is a conference speaker, technical proofreader for the ‘Kotlin In Action’ book, and author of the ‘Android Development with Kotlin’ book. Igor enjoys sharing his passion for coding with other developers.

Garima Jain

a Google Developer Expert in Android from India. She is also known around the community as @ragdroid. Garima works as a Principal Android Engineer at GoDaddy. She is also an international speaker and an active technical blogger. She enjoys interacting with other people from the community and sharing her thoughts with them. In her leisure time, she loves watching television shows, playing TT, and basketball. Due to her love for fiction and coding, she loves to mix technology with fiction and then shares her ideas with others through talks and blog posts.

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $14 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub