androidengineers.Book a session

LEARN WITH A CLEAR DIRECTION

Kotlin Coroutines

Asynchronous programming and concurrency in Android (modern best practices)

IntermediateSelf-paced16 modules0 available lessons

Your path, one skill at a time.

Kotlin Coroutines simplify async work with a clear, sequential style. This roadmap covers suspending functions, structured concurrency, Flow (cold) and StateFlow/SharedFlow (hot), lifecycle-aware collection, testing, and performance—everything you need to ship responsive Android apps.

What you’ll learn

  • Use suspending functions, scopes, and structured concurrency correctly
  • Choose the right Dispatcher and switch context with withContext
  • Model streams with Flow, and app state/events with StateFlow/SharedFlow
  • Collect safely using repeatOnLifecycle and collectAsStateWithLifecycle
  • Handle cancellation, timeouts, retries, and exceptions predictably
  • Test coroutines/flows with kotlinx-coroutines-test and Turbine
  • Know when to use Channels vs SharedFlow (no GlobalScope, no BroadcastChannel)

THE CURRICULUM

Everything you’ll learn, in order.

103 lessons and 17 labs across 16 modules. Lessons marked “Coming soon” aren’t available yet.

01Getting Started with Coroutines (Absolute Basics)5 lessons · 1 lab

Zero-prereq intro: mental model, first coroutine, basic suspend, and core terms.

  1. VideoWhat Are Coroutines? (not threads) — the mental modelComing soon
  2. VideoHello Coroutine: runBlocking + launch + delay (console demo)Coming soon
  3. Videosuspend Functions 101: writing & calling your first suspending APIComing soon
  4. LessonCheat Sheet: coroutine • job • scope • builder — quick definitionsComing soon
  5. LessonProject Setup (JVM & Android): coroutines-core/android + test libsComing soon
  6. LabPractice: two coroutines printing → refactor into a suspending functionComing soon
02Suspending & Builders — Foundations8 lessons · 1 lab

Clear separation of concepts: suspension vs blocking, builders, scope boundaries, and a first taste of structured concurrency.

  1. VideoSuspension vs Blocking: delay() vs Thread.sleep()Coming soon
  2. VideoSuspension Points in Practice: delay, I/O with withContext(Dispatchers.IO), Flow collect/emitComing soon
  3. VideoCooperative Cancellation: isActive, ensureActive, yield (keep work responsive)Coming soon
  4. VideoBuilders Deep Dive: launch vs async/await (returning results)Coming soon
  5. VideocoroutineScope vs supervisorScope: structure & child-failure behaviorComing soon
  6. VideoStructured Concurrency 101 (overview): parents, children, Job treesComing soon
  7. VideorunBlocking — when it’s OK (tests/main) and when it’s not (Android/UI)Coming soon
  8. LessonCheat Sheet: choosing a builder & scope (quick reference)Coming soon
  9. LabPractice: Parallel API calls with async + cancellation propagationComing soon
03Structured Concurrency — Deep Dive8 lessons · 2 labs

Principles, job hierarchies, failure propagation, supervision, and real-world scope design.

  1. VideoStructured Concurrency Principles (the key invariants)Coming soon
  2. VideoJob Hierarchies & Cancellation Trees (visual walkthrough)Coming soon
  3. VideoFailure Propagation: launch vs async (who cancels whom?)Coming soon
  4. VideoSupervisorJob vs supervisorScope: boundaries & use-casesComing soon
  5. VideoStructured Parallelism: async + awaitAll + cancellation on first failureComing soon
  6. VideoMultiple Failures, finally, and NonCancellable (cleanup patterns)Coming soon
  7. VideoAnti-patterns & Leaks: GlobalScope, orphan Jobs, ad-hoc scopesComing soon
  8. LessonScope Design Guide (UI, repo, use-case): who owns the scope?Coming soon
  9. LabPractice: Cancellation propagation lab (normal vs supervisor)Coming soon
  10. LabPractice: Parallel fan-out with fail-fast & proper cleanupComing soon
04Context & Dispatchers — Mastery9 lessons · 1 lab

Understand CoroutineContext deeply: elements, inheritance, dispatchers (Main/IO/Default/Unconfined), thread switching with withContext, limited parallelism, and thread-local propagation.

  1. VideoCoroutineContext 101: elements, + combination, inheritance & overridingComing soon
  2. VideoDispatchers: Main, IO, Default — when to use each (and why Unconfined is risky)Coming soon
  3. LessonAndroid specifics: Dispatchers.Main.immediate & main-safety notesComing soon
  4. VideowithContext correctly: switching threads without nesting traps; cancellation semanticsComing soon
  5. VideoTuning concurrency: Dispatchers.IO.limitedParallelism(n) and when to use itComing soon
  6. LessonCustom dispatchers: Executor.asCoroutineDispatcher vs newSingleThreadContext (trade-offs & cleanup)Coming soon
  7. VideoNaming & diagnostics: CoroutineName + structured loggingComing soon
  8. VideoThread context propagation: ThreadLocal.asContextElement / ThreadContextElement (MDC, request IDs)Coming soon
  9. LessonQuick note: CoroutineExceptionHandler is a context element (limitations for async)Coming soon
  10. LabPractice: Reduce context hops, add CoroutineName, wire MDC, and cap IO parallelismComing soon
05CoroutineStart Modes — Practical Control4 lessons · 1 lab

DEFAULT, LAZY, ATOMIC, UNDISPATCHED: how they start, when to use them, and common pitfalls.

  1. VideoThe start parameter on launch/async — what it controlsComing soon
  2. VideoDEFAULT vs LAZY — triggering start (start/join/await) & pitfalls in structured concurrencyComing soon
  3. VideoUNDISPATCHED — run on caller thread until first suspension (safer than Unconfined)Coming soon
  4. LessonATOMIC (Delicate) — guaranteed start before cancellation: use-cases & warningsComing soon
  5. LabPractice: Compare modes — warm-up jobs, lazy pipelines, and observing thread hopsComing soon
06Cancellation & Timeouts — Real-World Patterns8 lessons · 1 lab

Cooperative cancellation model, robust cleanup, timeouts that don’t bite you, and writing cancel-safe suspend APIs.

  1. VideoCancellation Model: Job.cancel, CancellationException, parent→child rulesComing soon
  2. VideoCooperative Cancellation in Practice: isActive, ensureActive, yield (CPU loops)Coming soon
  3. VideoCleanup Patterns: try/finally, withContext(NonCancellable), closing resources/channelsComing soon
  4. VideoTimeouts Deep Dive: withTimeout vs withTimeoutOrNull, propagation & common pitfallsComing soon
  5. VideoDesigning Cancel-Safe suspend APIs with suspendCancellableCoroutineComing soon
  6. LessonHooking Cancellation: invokeOnCancellation, listener removal, idempotent cleanupComing soon
  7. VideoCanceling Blocking Work: IO with withContext(Dispatchers.IO), interruptible ops, library caveatsComing soon
  8. VideoPolicy & Patterns: cancel vs retry, supervisor boundaries, time-budget designComing soon
  9. LabPractice: Build a cancel-safe repository (network + cache) with timeouts & retriesComing soon
07Exception Handling & Supervision — Mastery7 lessons · 1 lab

Understand how failures propagate, where exceptions surface, how supervision isolates errors, and how to build resilient retry logic.

  1. VideoException Model: child→parent propagation & who cancels whomComing soon
  2. Videolaunch vs async: where exceptions surface (handler vs await)Coming soon
  3. VideoCoroutineExceptionHandler: root-only behavior & limitations with async/supervisionComing soon
  4. LessonSupervisorJob vs supervisorScope: isolation boundaries & use-casesComing soon
  5. VideoMultiple Failures & Cancellation: suppressed exceptions, failures during cleanupComing soon
  6. VideoCancellation vs Failure: handling CancellationException vs real errors (rethrow patterns)Coming soon
  7. VideoRetries & Backoff (no Flow): exponential backoff, jitter, cancellation-aware delaysComing soon
  8. LabPractice: Fail-fast vs supervised trees + resilient use-case with retriesComing soon
08Shared Mutable State & Synchronization — Practical Patterns6 lessons · 1 lab

Avoid races with confinement, locks, semaphores, or actors. Keep critical sections tiny and responsive.

  1. VideoStrategies Overview: immutability, confinement, message passingComing soon
  2. VideoMutex.withLock: critical sections, tryLock, and “no blocking inside the lock”Coming soon
  3. VideoSemaphore.withPermit: limiting parallel work & rate limiting (vs limitedParallelism)Coming soon
  4. LessonSingle-threaded serialization: custom dispatcher/executor & cleanup dutiesComing soon
  5. VideoActors for Single-Owner State: when an actor beats locks; mailbox/backpressure basicsComing soon
  6. LessonChoosing the Right Tool: decision guide + fairness/starvation notesComing soon
  7. LabPractice: Controlled parallel downloads + shared progress counter (lock-free → mutex)Coming soon
09Flow Fundamentals6 lessons · 1 lab

Cold streams, terminal ops, cancellation transparency, and where work runs.

  1. VideoCold vs Hot — mental model & lifecycle (preview of StateFlow/SharedFlow)Coming soon
  2. Videoflow{} builder & terminal ops: collect, first/firstOrNull, single, toListComing soon
  3. VideoContext & execution: flowOn vs withContext (upstream-only) + exception transparencyComing soon
  4. LessonSide-effects & structure: onStart, onEach, onCompletion, emitAllComing soon
  5. VideoWrapping callbacks with callbackFlow: awaitClose, cancellation-safe cleanupComing soon
  6. VideochannelFlow vs callbackFlow — when to choose whichComing soon
  7. LabPractice: Debounced search pipeline (cold Flow)Coming soon
10Flow Operators & Backpressure6 lessons · 1 lab

Transform, combine, and control rate like a pro (with correct error semantics).

  1. VideoTransform basics: map, transform, transformLatest (when latest cancels prior work)Coming soon
  2. VideoFlatMap family: flatMapConcat / flatMapMerge / flatMapLatest — trade-offs & patternsComing soon
  3. VideoCombining streams: zip vs combine (+ combineTransform) — ordering & timingComing soon
  4. VideoRate control: buffer(capacity, onBufferOverflow), conflate, collectLatest, debounce, sampleComing soon
  5. LessonStateful ops: distinctUntilChanged/By, scan, runningFoldComing soon
  6. VideoError handling: catch placement (upstream/downstream), onCompletion, retry/retryWhenComing soon
  7. LabPractice: Performance-tuned pipeline (debounce + flatMapLatest + buffer)Coming soon
11Hot Flows: StateFlow & SharedFlow4 lessons · 1 lab

UI state, one-shot events, and sharing strategies done right.

  1. VideoStateFlow for UI State: replay=1, conflation, update()Coming soon
  2. VideoSharedFlow for Events: replay, extraBufferCapacity, onBufferOverflow (sticky vs non-sticky)Coming soon
  3. LessonTurning Cold → Hot: stateIn & shareIn with SharingStarted (Eagerly/Lazily/WhileSubscribed)Coming soon
  4. VideoScopes & Performance: where work runs with flowOn + stateIn/shareIn; avoid per-collector hot flowsComing soon
  5. LabPractice: ViewModel exposing StateFlow (UI state) + SharedFlow (one-shot events)Coming soon
12Lifecycle-Aware Collection (Android)4 lessons · 1 lab

Compose & View patterns that are safe, leak-free, and production-ready.

  1. VideoLaunching in Android: viewModelScope & lifecycleScope (ownership, boundaries, pitfalls)Coming soon
  2. VideoCompose: collectAsStateWithLifecycle (vs collectAsState), LaunchedEffect, rememberCoroutineScope, snapshotFlowComing soon
  3. VideoViews: repeatOnLifecycle (and why launchWhenX is discouraged)Coming soon
  4. LessonAvoiding Leaks & Duplicates: single source of truth, shareIn/stateIn, where to collectComing soon
  5. LabPractice: Build a lifecycle-safe screen (Compose + View example)Coming soon
13Channels — Pipelines & Point-to-Point5 lessons · 1 lab

Build producer–consumer pipelines with Channels and know when SharedFlow is the better fit.

  1. VideoChannel Types & Capacity: RENDEZVOUS / BUFFERED / CONFLATED / UNLIMITEDComing soon
  2. VideoSending & Receiving: send/receive, trySend/tryReceive, receiveCatchingComing soon
  3. VideoLifecycle: close vs cancel, iteration with for-loop, backpressure semanticsComing soon
  4. LessonPatterns: fan-in, fan-out, pipelines, fairness trade-offsComing soon
  5. VideoChannel vs SharedFlow: decision guide (point-to-point vs broadcast)Coming soon
  6. LabPractice: Multi-stage channel pipeline with multiple producers/consumersComing soon
14Integration: Networking, Storage, Background6 lessons · 1 lab

End-to-end Android patterns with coroutines: suspend networking, offline-first storage, paging, and background work.

  1. VideoRetrofit suspend APIs + serialization (Moshi / Kotlinx) & OkHttp interceptors/timeoutsComing soon
  2. VideoNetwork patterns: withContext(Dispatchers.IO), retries/backoff, error mapping (HTTP→Domain)Coming soon
  3. VideoRoom DAO with Flow: queries, transactions, and DTO → Entity → Domain mappingComing soon
  4. LessonSingle Source of Truth: cache-then-network, invalidation, and sync strategiesComing soon
  5. VideoPaging 3 in practice: Pager, PagingSource, RemoteMediator, load states, cachedIn(viewModelScope)Coming soon
  6. VideoBackground work: WorkManager CoroutineWorker (cancellation, progress, constraints) vs Foreground serviceComing soon
  7. LabPractice: Offline-first repository (Retrofit + Room + Paging RemoteMediator) with retry & background syncComing soon
15Testing Coroutines & Flows — From Zero to Flake-Free10 lessons · 1 lab

Deterministic, fast, and reliable tests with kotlinx-coroutines-test and Turbine.

  1. VideoTest Dispatchers 101: StandardTestDispatcher vs UnconfinedTestDispatcherComing soon
  2. VideorunTest & Virtual Time: scheduler, advanceTimeBy, runCurrent, advanceUntilIdleComing soon
  3. LessonMainDispatcherRule (JUnit4/JUnit5) & swapping Dispatchers.Main safelyComing soon
  4. VideoTesting suspend functions: success, exceptions, cancellationComing soon
  5. VideoTesting Cold Flows: terminal ops, flowOn, catch placementComing soon
  6. VideoTesting Hot Flows (StateFlow/SharedFlow): backgroundScope, replay, buffer, timingComing soon
  7. VideoTurbine Patterns: awaitItem, skipItems, expectNoEvents, timeouts, cancelAndIgnoreRemainingEventsComing soon
  8. VideoTime-based Operators: debounce, sample, retry/backoff with virtual timeComing soon
  9. LessonChannels & select in tests: send/receive, closing, and race scenariosComing soon
  10. VideoFlake-proofing: deterministic scheduling, avoid real delays, leak checks with TestScopeComing soon
  11. LabPractice: Repo Flow tests (retry + timeout) + StateFlow UI state with TurbineComing soon
16Performance, Patterns & Capstones — Ship It7 lessons · 1 lab

Make it fast and resilient, then apply everything in real projects.

  1. VideoMinimize context hops & avoid needless withContext (throughput & readability)Coming soon
  2. VideoTuning parallelism: Dispatchers.IO.limitedParallelism(n) vs Semaphore.withPermitComing soon
  3. VideoBackpressure in hot streams: StateFlow/SharedFlow buffer, overflow, replay sizingComing soon
  4. VideoDetecting cancellation leaks & logging coroutine trees (diagnostics playbook)Coming soon
  5. LessonPattern catalog: retries/backoff, time budgets, circuit breaker & hedgingComing soon
  6. VideoCapstone A: Offline-First Search (Flow + Room + retries)Coming soon
  7. VideoCapstone B: Downloader (callbackFlow + StateFlow, pause/resume/cancel)Coming soon
  8. LabPractice: Implement one capstone end-to-end (repo, tests, perf checks)Coming soon