Kotlin Coroutines
Kotlin Coroutines
Deep Dive
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.
Bundles that include this book
About the Contributors
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.
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.
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.
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.
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.
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.
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.
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.
Table of Contents
-
Introduction
- Who is this book for?
- The structure of this book
- What will be covered?
- The Kotlin for Developers series
- Conventions
- Code conventions
- Version
- Exercises and solutions
- Acknowledgments
- Part 1: Understanding Kotlin Coroutines
-
Why Kotlin Coroutines?
- Simplicity
- Performance
- Cancellation
- Synchronization
- Testability
- Flow
- Coroutines are multiplatform
- The biggest problem with Kotlin Coroutines
- Summary
-
Sequence builder
- Real-life usages
- Exercise: Factorial sequence
- Exercise: Prime numbers sequence
-
How does suspension work?
- A game analogy
- Suspending functions
- Your first suspension
- What is stored in the continuation?
- Delaying a coroutine
- Resuming with a value
- Resume with an exception
- Suspending a coroutine, not a function
- Summary
- Exercise: Callback function wrappers
- Exercise: Continuation storage
-
Coroutines under the hood
- Continuation-passing style
- A very simple function
- A function with a state
- A function resumed with a value
- The call stack
- The actual code
- The performance of suspending functions
- Summary
- Exercise: What is stored by a continuation?
- Coroutines: built-in support vs library
- Part 2: Kotlin Coroutines library
-
Starting coroutines
- Asynchronous coroutine builders
- Blocking coroutine builders
- Structured Concurrency
- Coroutine scope functions
- Summary
- Exercise: UserDetailsRepository
- Exercise: BestStudentUseCase
- Exercise: CommentService
- Exercise: mapAsync
- The bigger picture
-
Coroutine context
-
CoroutineContext
interface - Finding elements in CoroutineContext
- Adding contexts
- Empty coroutine context
- Subtracting elements
- Folding context
- Coroutine context and builders
- Accessing context in a suspending function
- Changing context in suspending functions
- Creating our own context
- Coroutines and thread elements
- Summary
- Exercise: Understanding context propagation
- Exercise: CounterContext
-
-
Dispatchers
- Default dispatcher
- Limiting the default dispatcher
- Main dispatcher
- IO dispatcher
- Dispatcher with a custom limit
- Dispatcher with a fixed pool of threads
- Dispatcher limited to a single thread
- Using virtual threads from Project Loom
- Unconfined dispatcher
- Immediate main dispatching
- Continuation interceptor
- Performance of dispatchers when executing different tasks
- Summary
- Exercise: Using dispatchers
- Exercise: DiscNewsRepository
- Exercise: Experiments with dispatchers
-
Job and coroutine lifecycle
- Job and relationships
- Coroutine lifecycle
- Awaiting job completion
- The Job factory function
- Synchronizing coroutines
- Summary
-
Cancellation
- Basic cancellation
-
The
finally
block - invokeOnCompletion
- Cancellation of children
- Cancellation in a coroutine scope
- Just one more call
- Stopping the unstoppable
- CancellationException is special
- CancellationException does not propagate to its parent
- withTimeout
-
suspendCancellableCoroutine
- Summary
- Exercise: Correct mistakes with cancellation
-
Exception handling
- Exceptions and structured concurrency
- SupervisorJob
- supervisorScope
- Exceptions and await call
-
CoroutineExceptionHandler
- Summary
-
Constructing a coroutine scope
- CoroutineScope factory function
- Constructing a background scope
- Constructing a scope on Android
- Summary
- Exercise: NotificationSender
- Exercise: BaseViewModel
-
Synchronizing access to mutable state
- Using atomic values
- Synchronized blocks
- Using a dispatcher limited to a single thread
- Mutex
- Semaphore
- Summary
- Exercise: CompanyDetailsRepository
- Exercise: CancellingRefresher
- Exercise: TokenRepository
- Exercise: Suspended lazy
- Exercise: mapAsync with concurrency limit
-
Testing Kotlin Coroutines
- Testing time dependencies
-
TestCoroutineScheduler
andStandardTestDispatcher
- runTest
- Background scope
- Testing cancellation and context passing
-
UnconfinedTestDispatcher
- Using mocks
- Testing functions that change a dispatcher
- Testing what happens during function execution
- Testing functions that launch new coroutines
- Replacing the main dispatcher
- Testing Android functions that launch coroutines
- Setting a test dispatcher with a rule
- Summary
- Exercise: Test UserDetailsRepository
- Exercise: Testing mapAsync
- Exercise: Testing the NotificationSender class
- Exercise: Testing a View Model
- Part 3: Channel and Flow
-
Channel
- Channel types
- On buffer overflow
- On undelivered element handler
- Fan-out
- Fan-in
- Pipelines
- Practical usage
- Summary
- Exercise: UserRefresher
- Exercise: Cafeteria simulation
-
Select
- Selecting deferred values
- Selecting from channels
- Summary
- Exercise: raceOf
-
Hot and cold data sources
- Hot vs cold
- Hot channels, cold flow
- Summary
-
Flow introduction
- Comparing flow to other ways of representing values
- The characteristics of Flow
- Flow nomenclature
- Real-life use cases
- Summary
-
Understanding
Flow
-
Understanding
Flow
-
How
Flow
processing works - Flow is synchronous
- Flow and shared state
- Conclusion
-
Understanding
-
Flow building
- Flow from raw values
- Converters
- Converting a function to a flow
- Flow and Reactive Streams
- Flow builders
- Understanding flow builder
- channelFlow
- callbackFlow
- Summary
- Exercise: Flow utils
- Exercise: All users flow
- Exercise: distinct
-
Flow lifecycle functions
- onEach
- onStart
- onCompletion
- onEmpty
- catch
- Uncaught exceptions
-
retry
- flowOn
- launchIn
- Summary
- Exercise: TemperatureService
- Exercise: NewsViewModel
-
Flow processing
-
map
-
filter
-
take
anddrop
- How does collection processing work?
-
merge
,zip
andcombine
-
fold
andscan
-
flatMapConcat
,flatMapMerge
andflatMapLatest
- Distinct until changed
-
buffer
andconflate
-
debounce
-
sample
- Terminal operations
- Summary
- Exercise: ProductService
- Exercise: Flow Kata
- Exercise: MessageService
-
-
SharedFlow and StateFlow
- SharedFlow
-
shareIn
- StateFlow
-
stateIn
- Summary
- Exercise: Update ProductService
- Exercise: Update TemperatureService
- Exercise: LocationService
- Exercise: PriceService
- Exercise: NewsViewModel using stateIn
-
Testing flow
- Transformation functions
- Testing infinite flows
- Determining how many connections were opened
- Testing view models
- Summary
- Exercise: Flow testing
- Part 4: Kotlin Coroutines in practice
-
Common use cases
- Data/Adapters Layer
- Domain Layer
- Presentation/API/UI layer
- Summary
-
Using coroutines from other languages
- Threads on different platforms
- Transforming suspending into non-suspending functions
- Calling suspending functions from other languages
- Flow and Reactive Streams
- Summary
- Launching coroutines vs. suspending functions
- Best practices
- The End
- Exercise solutions
- Notes
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 earnedover $14 millionwriting, 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