Coroutines
46 bites tagged Coroutines — interview questions with model answers, and 60-second explainers.
Explain the asyncio event loop and cooperative multitasking
Tests if you view the event loop as a single-threaded orchestrator, not magic parallelism. Strong answers note it runs tasks and callbacks, manages a ready queue, and yields control at await. Red flag: calling it multithreading or parallel execution.
What is the difference between async def and regular functions?
This tests async def call semantics. A strong answer contrasts regular functions, which execute immediately, with async def, which returns a coroutine object that does nothing until awaited or wrapped in create_task.
What is the role of TestDispatcher and runTest in coroutine testing?
This tests coroutine test infrastructure and virtual time control. A great answer says runTest installs a TestDispatcher and TestScope, skips delays automatically, and exposes advanceTimeBy to test timeouts instantly.
Explain Structured Concurrency in Kotlin Coroutines
Structured concurrency binds coroutines to a scope; parent cancellation propagates to all children, preventing leaks. your grasp of Kotlin coroutine parent-child scope hierarchies. calling them unmanaged threads.
What is the difference between viewModelScope and lifecycleScope?
This tests scope ownership across configuration changes. viewModelScope survives rotation because it lives in ViewModel, while lifecycleScope dies with UI; use former for logic and latter for UI tasks. Never launch data loads in lifecycleScope.
How do you make a network request in an Activity using coroutines?
This tests main thread safety and coroutine dispatchers. A strong answer cites NetworkOnMainThreadException, uses lifecycleScope, and switches to Dispatchers.IO. Red flag: suggesting Dispatchers.Main for the network call or omitting the exception entirely.
How do you differentiate network and server errors in suspend functions?
Catch IOException for connectivity and HttpException for HTTP errors; wrap in a sealed Result. Structured error handling in coroutines and mapping exceptions to recovery. Catching Exception or exposing raw errors to UI.
Room DAO: Flow<List<User>> vs suspend fun getUsers(): List<User>
This tests reactivity versus one-shot queries in Room and coroutines. Flow emits on every table change on Room's dispatcher, while suspend returns a single snapshot requiring manual refresh.
Which side-effect handler for a one-time coroutine on composition entry?
Tests Compose side-effect API boundaries. Answer: LaunchedEffect(Unit); it runs once and auto-cancels on exit. Contrast with rememberCoroutineScope for user-triggered callbacks. Red flag: picking SideEffect or rememberCoroutineScope and missing cancellation.
Describe coroutine cancellation mechanics and cooperative suspend functions
Tests cooperative cancellation mechanics. cancel() sets a Job to cancelling; suspend functions check this at suspension points and throw CancellationException, yet a tight non-suspending loop never checks and keeps running.
How do buffer, conflate, and collectLatest manage Kotlin Flow backpressure?
Backpressure is fast emit vs slow collect; buffer() suspends the producer when full, conflate() drops stale values, and collectLatest() cancels active collection to… Coroutine flow control and suspension-vs-dropping tradeoffs.
What is a CoroutineDispatcher and when to use Default versus IO?
This tests thread pool selection and the CPU versus IO distinction. A strong answer maps CoroutineDispatcher to the thread pool, Default to CPU work, IO to blocking IO, and Main to the UI thread.
Hot vs cold Kotlin Flows and StateFlow use case
Tests grasp of flow lifecycle and collector behavior. A strong answer contrasts cold Flows, which restart per collector, with hot StateFlows broadcasting to all observers. Red flag: using Flow for UI state without citing config changes or initial value.
How does Structured Concurrency handle cancellations and exceptions?
This tests scope-bound lifecycle management preventing leaks. Cover scope cancellation cascading to children, exceptions propagating up to cancel siblings, and launch or async requiring a scope. A red flag is treating coroutines as fire-and-forget threads.
What is a suspend function in Kotlin and its compiler rules?
This tests your understanding of suspendable computations and compiler transformation. A strong answer notes non-blocking suspension, the call-from-suspend-context rule, and compiler support for pausing and resuming. A red flag is claiming they block threads.
Explain the difference between launch and async in Kotlin Coroutines
This tests scope behavior and side effects versus results. A strong answer says launch returns a Job for side effects, async returns a Deferred for results, and both are scope children. A red flag is using async for all tasks or ignoring exception handling.
Combine two network sources using Coroutines and Flow
Tests your grasp of async data combination and state management. A good answer uses Flow.combine in a ViewModel, fed by a Repository, emitting a sealed class for UI state (Loading, Success, Error). A red flag is trying to combine state in the UI layer itself.
Which Compose side-effect for a one-time coroutine action?
Tests if you can choose the right Compose side-effect for a one-time coroutine. A great answer names `LaunchedEffect(Unit)`, explains it runs once and cancels on exit. A red flag is suggesting `rememberCoroutineScope` directly in the composable body.
How does coroutine cancellation work internally?
Tests your grasp of cooperative cancellation. A good answer explains that `cancel()` sets a flag, `suspend` functions check it and throw `CancellationException`, and non-suspending loops need manual `isActive` checks.
Explain backpressure in Kotlin Flows and its management operators
This tests your understanding of Flow's pull-based nature and performance tuning. A great answer defines suspension as the default backpressure, then details how `buffer`, `conflate`, and `collectLatest` optimize it.
What is a CoroutineDispatcher and when do you use each type?
Tests your grasp of coroutine threading. A dispatcher manages which threads a coroutine runs on. Explain `Main` for UI, `Default` for CPU-intensive work, and `IO` for blocking operations. A red flag is mixing up `IO` and `Default` or using `Unconfined`.
Hot vs. Cold Streams: `StateFlow` vs. `Flow`
Tests your grasp of stream lifecycles. A great answer defines cold `Flow` (lazy, per-collector) vs. hot `StateFlow` (shared, active), then uses a ViewModel UI state scenario to show why `StateFlow` is correct for surviving configuration changes.
Structured Concurrency in Kotlin Coroutines
Tests your understanding of coroutine lifecycles and error handling. A good answer defines the parent-child relationship, then explains how cancellation and exceptions propagate through the scope. A red flag is simply calling it a way to 'group' coroutines.
What is a `suspend` function in Kotlin?
Tests your grasp of Kotlin's core concurrency primitive. A `suspend` function can pause and resume. It must be called from another suspend function or a coroutine builder.
Get Coroutines bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.