Kotlin Coroutines, Flow, and Compose Internals
Problem Explain how Kotlin Coroutines, Flow, and Jetpack Compose work under the hood.
Be ready to discuss
- Coroutines as lightweight threads: the compiler rewrites each
suspendfunction into a state machine (Continuation Passing Style), so suspending parks the coroutine without blocking the underlying OS thread. - Suspension points and continuations: what
suspendactually compiles to, and why a suspended coroutine costs only a heap object rather than a thread stack. - Dispatchers:
Main,IO, andDefault, which thread pool each maps to, and howwithContextmoves work between them. - Structured concurrency: the CoroutineScope/Job hierarchy, parent-child cancellation propagation,
SupervisorJob, and why scope prevents leaks. - Flow as a cold asynchronous stream: nothing runs until
collect, each collector gets its own execution, and operators likemap/filter/combineare suspend-friendly. - Cold vs hot:
StateFlow(conflated, always has a value) andSharedFlow(configurable replay) for observable state, andflowOnfor upstream dispatch. - Compose as declarative UI: composables describe UI as a function of state, and the Snapshot system records which state each composable reads.
- Recomposition: only composables whose observed state changed re-run, and the Slot Table (a gap buffer) stores composition structure so Compose can diff and patch without a View hierarchy.
- Why composables must be side-effect free and idempotent - recomposition can run often, out of order, and be skipped entirely.
asked …