Coroutines are where Android interviews separate people who have used Kotlin from people who have read about it. Almost every app does network and database work, and the interviewer wants to know you can do it without leaking work, blocking the main thread or swallowing errors. These are the coroutine and Flow questions I see most often, with answers and short code.
Coroutine basics
1. What is a coroutine?
A coroutine is a block of code that can suspend and resume later without blocking the thread it runs on. Thousands of coroutines can share a few threads, because a suspended coroutine does not hold its thread. It is not a thread; it is closer to a lightweight, cancellable task managed by the Kotlin library.
2. What does suspend actually do?
It marks a function that may pause. The compiler rewrites it in continuation-passing style: it adds a hidden Continuation parameter and turns the body into a state machine, so the function can return when it suspends and continue from the right point when resumed. suspend alone does not move work to a background thread; a suspend function that does heavy CPU work still blocks whichever thread runs it.
3. What is the difference between launch and async?
viewModelScope.launch {
val profile = async { repo.profile(id) }
val posts = async { repo.posts(id) }
_uiState.value = UiState.Success(profile.await(), posts.await())
}
launch returns a Job and is for work with no result. async returns a Deferred<T> and is for parallel work whose result you need; call await(). Here the two requests run concurrently, so the total time is the slower of the two, not their sum.
4. What is runBlocking and when is it acceptable?
It starts a coroutine and blocks the current thread until it finishes. It bridges blocking and suspending code: acceptable in main() functions and some tests, never on the Android main thread. For tests, prefer runTest from kotlinx-coroutines-test, which skips delay with virtual time.
Context and dispatchers
5. What are dispatchers?
A dispatcher decides which thread or pool runs a coroutine:
Dispatchers.Main: the Android UI thread.Main.immediateavoids re-dispatching if you are already on main.Dispatchers.IO: a pool for blocking I/O such as files and legacy blocking APIs. It can grow to 64 threads by default.Dispatchers.Default: a pool sized to the CPU cores, for CPU-heavy work like sorting or parsing large JSON.Dispatchers.Unconfined: not for normal app code.
6. How do you switch threads inside a coroutine?
With withContext:
class ArticleRepository(
private val api: ArticleApi,
private val io: CoroutineDispatcher = Dispatchers.IO,
) {
suspend fun load(id: String): Article = withContext(io) {
api.fetch(id)
}
}
The good practice to mention: make suspend functions main-safe (callers can call them from the main thread), and inject the dispatcher so tests can replace it with a test dispatcher. Retrofit and Room already expose main-safe suspend functions, so you do not need withContext(IO) around them.
7. What is CoroutineContext?
An indexed set of elements: a Job, a CoroutineDispatcher, a CoroutineName, a CoroutineExceptionHandler. Elements combine with +. A child coroutine inherits its parent's context, with a new Job that is a child of the parent's.
Structured concurrency and scopes
8. What is structured concurrency?
Every coroutine runs in a scope, and coroutines form a parent-child tree. A parent does not complete until all children complete; cancelling a parent cancels its children; a failing child (by default) cancels its parent and siblings. Work cannot silently outlive the thing that started it.
9. Which scopes do you use on Android?
viewModelScope: cancelled inonCleared(). Most business work starts here.lifecycleScope: tied to an Activity or Fragment lifecycle.rememberCoroutineScope()in Compose: tied to the composition.- For work that must outlive a screen, an application-level scope you create and inject, or WorkManager for work that must survive process death.
10. Why not use GlobalScope?
It has no lifecycle, so nothing cancels it. A request started there keeps running after the user leaves the screen, can update dead UI and holds references longer than it should. It also breaks structured concurrency, so errors are not propagated to anyone who cares.
11. What is the difference between coroutineScope and supervisorScope?
Both are suspend functions that create a child scope and wait for all children. In coroutineScope, if one child fails, the others are cancelled and the exception is rethrown. In supervisorScope, a child failure does not cancel its siblings. Use supervisorScope when tasks are independent, such as loading several dashboard widgets where one failing should not blank the rest. viewModelScope uses a SupervisorJob for the same reason.
Cancellation and exceptions
12. How does cancellation work?
Cancellation is cooperative. Calling job.cancel() marks the job as cancelled; the coroutine stops at the next suspension point that checks for cancellation (delay, withContext, yield, most library suspend functions), which throws CancellationException. A tight CPU loop must check itself:
suspend fun crunch(data: List<Int>) = withContext(Dispatchers.Default) {
for (item in data) {
ensureActive() // throws if cancelled
process(item)
}
}
13. Why should you not catch CancellationException and ignore it?
Because that stops cancellation from propagating, and the coroutine keeps running when it should have stopped. A broad catch (e: Exception) around a suspend call catches it too. Either rethrow CancellationException, or catch specific exceptions such as IOException. runCatching around suspend calls has the same problem.
14. How do you run cleanup code that must suspend after cancellation?
In finally, wrapped in withContext(NonCancellable) { }, because a cancelled coroutine cannot suspend normally.
15. How are exceptions handled in launch vs async?
In launch, an uncaught exception propagates up to the parent and, at the root, to a CoroutineExceptionHandler or the thread's uncaught exception handler (a crash on Android). In async, the exception is held in the Deferred and thrown on await(); but as a child in a regular scope it still cancels the parent. CoroutineExceptionHandler only works when installed on a root coroutine or a supervisor's direct child; installing it on a nested launch does nothing. For most app code, catch expected errors with try/catch inside the coroutine and map them to an error state.
Flow
16. What is a Flow?
A Flow<T> is an asynchronous stream of values computed sequentially. It is to coroutines what Sequence is to collections. It is cold by default:
fun ticker(periodMs: Long): Flow<Int> = flow {
var n = 0
while (true) {
emit(n++)
delay(periodMs)
}
}
Nothing runs until someone calls a terminal operator like collect, first or toList.
17. Cold flow vs hot flow?
A cold flow runs its producer separately for each collector, starting when collection starts. Two collectors of the ticker above each get their own counter. A hot flow (StateFlow, SharedFlow) exists independently of collectors, and all collectors share the same emissions.
18. StateFlow vs SharedFlow vs LiveData?
StateFlow<T>: always has a value, new collectors get the latest value immediately, and equal consecutive values are skipped (conflated). The default choice for UI state.SharedFlow<T>: configurablereplayand buffer, no initial value, emits every value. Used for broadcasts.LiveData: lifecycle-aware and Android-only. Still found in older code; new Kotlin code generally prefersStateFlow, collected with lifecycle awareness.
class SearchViewModel(private val repo: SearchRepository) : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Idle)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
}
Expose the read-only type; keep the mutable one private.
19. How do you handle one-off events like navigation or a snackbar?
There are two accepted answers, and saying both shows maturity. Google's current guidance is to model events as state: put a field like userMessage in the UI state and have the UI call back to clear it once shown. The other common approach is a Channel exposed with receiveAsFlow(), which delivers each event to one collector. A SharedFlow with replay = 0 can lose events emitted while no one is collecting, which is why it is a weaker choice for this.
20. What do stateIn and shareIn do?
They convert a cold flow into a hot StateFlow or SharedFlow within a scope:
val uiState: StateFlow<UiState> = repo.observeItems()
.map { UiState.Success(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UiState.Loading,
)
WhileSubscribed(5_000) keeps the upstream alive for five seconds after the last collector leaves, so a screen rotation does not restart the database query, but going to the background does stop it.
21. How do you collect a Flow safely in the UI?
In Compose, collectAsStateWithLifecycle(). In Views, repeatOnLifecycle:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { render(it) }
}
}
Plain lifecycleScope.launch { flow.collect { } } keeps collecting while the app is in the background, wasting resources and possibly updating views that are not visible.
22. flatMapLatest vs flatMapConcat vs flatMapMerge?
All map each value to a new flow. flatMapConcat collects them one after another. flatMapMerge collects them concurrently. flatMapLatest cancels the previous inner flow when a new value arrives. Classic use of flatMapLatest: search as you type, combined with debounce:
val results = queryFlow
.debounce(300)
.distinctUntilChanged()
.flatMapLatest { q -> repo.search(q) }
23. What do combine and zip do?
combine emits whenever any source emits, using the latest value from each; use it to build UI state from several streams. zip pairs values one-to-one and waits for both.
24. What does flowOn do?
It changes the dispatcher for the operators upstream of it, not downstream. flow { heavyRead() }.flowOn(Dispatchers.IO).collect { } runs the producer on IO and the collector in the caller's context. Never use withContext inside a flow { } builder to emit from another context; that violates context preservation and throws.
25. How do you handle errors in a Flow?
With catch for upstream errors, which can emit a fallback value, and retry or retryWhen for retries. catch does not catch exceptions thrown in the collector; put the logic in onEach before catch, or use try/catch around collect. onCompletion runs on success, failure or cancellation.
26. What are buffer, conflate and collectLatest?
Backpressure tools. buffer() lets the producer run ahead of a slow collector. conflate() drops intermediate values so the collector only sees the latest. collectLatest { } cancels the collector's previous block when a new value arrives.
27. How do you test coroutines and flows?
runTest with a StandardTestDispatcher or UnconfinedTestDispatcher, Dispatchers.setMain(testDispatcher) for ViewModels that use viewModelScope, and injected dispatchers for repositories. For flows, collect into a list or use a library like Turbine to assert emissions in order.
The answer interviewers want under all of this
Every question above comes back to three ideas: work belongs to a scope, cancellation is cooperative and must not be swallowed, and UI should observe state through lifecycle-aware collection. If you can explain those with your own code, you will handle the follow-ups.
Next, read the Android architecture interview questions, where coroutines and Flow meet ViewModels and repositories, or go back to the Kotlin interview questions.
Practise this with a trainer
Coroutines click fastest when you debug real cancellation and error cases with someone who can explain what you are seeing. Our Kotlin training in Chennai and Android training in Chennai cover coroutines and Flow on real app code. See all programs.
K P Ranjith Kumar is a former Google Certified Associate Android Developer and the founder of TechManifester. He has taught Android and Kotlin for over 12 years.