Coroutines, structured concurrency, Flow, StateFlow, SharedFlow, and channels
Simple idea
A coroutine is cancellable work that may suspend without blocking its thread. Structured concurrency gives that work an owner. Flow represents asynchronous values over time; StateFlow stores current state; SharedFlow broadcasts events/values; channels send values between coroutines.
Chapter pages
- Suspending functions and coroutine basics
- How a coroutine executes: thread, suspension, dispatcher, and Job
- Structured concurrency, cancellation, and errors
- Cancellation and exception propagation in detail
- Dispatchers and coroutine context
- Flow foundations
- Flow execution, operators, context, and search pipelines
- Buffering, backpressure, callbackFlow, and retry
- StateFlow, SharedFlow, and channels
- State and event delivery guarantees
- Lifecycle, testing, production scenarios, and interviews
How to study this chapter
Do not memorize operator names first. For every example, answer:
- Who owns this work and when is it cancelled?
- Which part suspends, blocks, or consumes CPU?
- Which dispatcher executes each part?
- How do failure and cancellation propagate?
- Is every value required, replaceable, or allowed to be lost?
- What happens when the collector disappears, the process dies, or the account changes?
Those questions turn coroutine syntax into production concurrency design.
Examples in this chapter use kotlinx.coroutines. Android examples also require AndroidX lifecycle/ViewModel libraries, so dependency-specific snippets are labeled rather than linked to a dependency-free Playground.