Intermediate Android interview questions

152 questions from the Intermediate lessons. Open a question to see the junior, mid and senior answers. Each one links to the lesson that explains it.

Coroutines and Flow

What does the suspend keyword actually do at compile time?
Junior
It marks a function that can pause without blocking a thread. You can only call a suspend function from another suspend function or from a coroutine builder like launch.
Mid
The compiler adds a Continuation parameter and turns the body into a state machine, with one state per suspension point. When a call actually suspends, the function stores its local variables in the continuation object and returns COROUTINE_SUSPENDED, so the thread is free for other work. When the awaited result is ready, resume() is called and the coroutine's dispatcher decides which thread continues the function.
Senior
Two things suspend does not do. It does not move work off the main thread: a suspend function that calls blocking I/O still blocks its thread, so main-safety comes from withContext at the point of the blocking call. And it does not add cancellation checks: the compiler inserts none. Cancellation is checked by library suspend functions such as delay, yield and anything built on suspendCancellableCoroutine, so a CPU loop with no suspension points cannot be cancelled until it calls ensureActive() or yield(). You can see the rewrite with Show Kotlin Bytecode and Decompile in Android Studio: an extra Continuation parameter, an Object return type and a switch over a label field.
Learn it: Coroutines basics: suspend and builders
When do you use async instead of launch?
Junior
Use async when you need the result of the coroutine. It returns a Deferred<T> that you call await() on. launch returns a Job and is for fire-and-forget work.
Mid
async is for running work in parallel and combining the results: start two async blocks, then await() both, and the total time is the slower of the two rather than the sum. await() suspends until the value is ready and rethrows the exception if the block failed. A child async that fails also cancels its parent straight away, whether or not anyone has called await() yet.
Senior
I use async for fan-out inside a coroutineScope: start the independent calls, then awaitAll. The coroutineScope makes the failure behaviour clear: one failure cancels the other calls and the exception comes out of coroutineScope, where one try/catch handles it. Writing val a = async { x() }.await() is just a slower way to call x(). The surprising case is async in a supervisorScope or as a root coroutine: there the exception is kept in the Deferred and only thrown by await(), so a Deferred that is never awaited hides the failure completely. For a single call whose result I need, I call the suspend function directly.
Learn it: Coroutines basics: suspend and builders
What is the difference between coroutineScope and supervisorScope?
Junior
coroutineScope cancels all children if one child fails. supervisorScope lets siblings continue even if one child fails.
Mid
Both create a new scope whose Job is a child of the caller's Job, and both wait for all their children. In coroutineScope, a failing child cancels the scope, which cancels every sibling, and the exception is rethrown to the caller. supervisorScope uses supervisor behaviour: a failing child does not cancel the scope or its siblings. The usual pitfall is using coroutineScope for unrelated calls where one error should not kill the others.
Senior
The question is whether the tasks share a fate. Steps that only make sense together (fetch a token, then use it) belong in coroutineScope so one failure aborts the rest. Independent sections of a screen belong in supervisorScope. The cost of supervisorScope is that nobody handles a child's error for you: a failed launch child goes to the CoroutineExceptionHandler in its context, or to the thread's uncaught exception handler, which crashes an Android app. So each child catches its own errors, or uses async and the caller wraps await() in try/catch. Also, supervisorScope itself still fails if its own block throws, and cancelling the caller still cancels all its children.
Learn it: Coroutines basics: suspend and builders
Why must CancellationException be rethrown?
Junior
Cancellation reaches your code as a CancellationException thrown from a suspend call like delay. If you catch it and carry on, your code keeps running after the screen is gone, for example updating state or showing an error for a request the user abandoned.
Mid
Catching the exception does not un-cancel the Job. The coroutine is still cancelled, so the next cancellable suspension point throws again, but the code in between runs as a zombie. A loop that catches everything spins, and a parent that calls cancelAndJoin() waits until that child really finishes. So catch specific exceptions, or rethrow CancellationException before a generic catch.
Senior
runCatching and catch (e: Exception) are the usual culprits, so I look for them around suspend calls in review. Where a catch-all is needed, I rethrow CancellationException or call coroutineContext.ensureActive() in the catch. The reverse matters too: a CancellationException is treated as normal cancellation, not failure, so throwing one to report a real error makes that error disappear without reaching any handler. For suspend cleanup in finally I use withContext(NonCancellable), and only for short work like closing a resource, because that block cannot be stopped.
Learn it: Coroutines basics: suspend and builders
What is the difference between Dispatchers.IO and Dispatchers.Default?
Junior
IO is for network or disk tasks and Default is for heavy calculations.
Mid
Default is sized for CPU work: one thread per core, at least two. IO is for blocking calls and allows up to 64 tasks at once by default (or the core count if that is higher), because threads that are blocked waiting use almost no CPU. Using the wrong one either starves the CPU pool with blocked threads or runs far more CPU tasks than there are cores.
Senior
They are two views of one shared thread pool with different limits, so withContext(Dispatchers.IO) from Default often stays on the same thread and the switch is cheap. The IO limit is set with the kotlinx.coroutines.io.parallelism system property. Views of IO made with limitedParallelism are elastic: they are not counted against IO's 64, so I give a slow blocking SDK its own Dispatchers.IO.limitedParallelism(4) and it cannot use up the shared IO slots. Default.limitedParallelism(n), by contrast, can never exceed Default's own size. limitedParallelism limits how many coroutines run at once, not which threads they use, and it is not a mutex: a suspended coroutine gives up its slot.
Learn it: Dispatchers and threading
How do you make a suspend function main-safe?
Junior
Use withContext(Dispatchers.IO) inside the function around the blocking call.
Mid
Wrap only the blocking or heavy part in withContext with the right dispatcher, IO for blocking calls and Default for CPU work, inside the class that does the work. Then the caller, usually a ViewModel on the main thread, never needs to think about threads.
Senior
The class that knows the work is blocking owns the switch, so repositories and data sources are main-safe and ViewModels stay on Main.immediate. I do not wrap calls that are already main-safe, such as Room or Retrofit suspend functions, and I avoid switching in the ViewModel. The dispatchers are constructor parameters with production defaults, so tests can pass a StandardTestDispatcher that shares the runTest scheduler. And main-safe is not thread-safe: two callers can still run the function at the same time, so shared mutable state needs a Mutex or an atomic update.
Learn it: Dispatchers and threading
What happens if you call a blocking function like Thread.sleep() inside a coroutine on Dispatchers.Main?
Junior
The app freezes: nothing redraws and taps do nothing until the sleep ends.
Mid
It blocks the main thread, which handles drawing and input. Short blocks cause dropped frames; if an input event is not handled within about 5 seconds, the system shows an ANR dialog. Use delay instead, which suspends without blocking.
Senior
The main dispatcher is one thread running a message queue. A suspended coroutine lets other messages run, but a blocked thread processes nothing: no frames, no input, no other coroutines on Main. Thread.sleep also ignores coroutine cancellation, so the coroutine cannot stop early. I look for hidden blocking calls on Main too, like SharedPreferences commit, synchronous file reads or a blocking SDK, using StrictMode in debug builds and ANR traces from Play Console.
Learn it: Dispatchers and threading
Why should you inject Dispatchers instead of using the static Dispatchers object?
Junior
So tests can use a different dispatcher.
Mid
A test can pass a TestDispatcher that shares the runTest scheduler, so work runs in a predictable order and delay is skipped with virtual time. Hardcoded Dispatchers.IO runs on real threads that the test cannot control.
Senior
I inject a CoroutineDispatcher with a production default, often with Hilt qualifiers like @IoDispatcher, so tests and production share code paths. StandardTestDispatcher queues work until the scheduler runs it, which is good for checking intermediate states; UnconfinedTestDispatcher runs eagerly, which is simpler for collectors. viewModelScope always uses Dispatchers.Main, which cannot be injected, so ViewModel tests also call Dispatchers.setMain in a JUnit rule and resetMain afterwards.
Learn it: Dispatchers and threading
What is structured concurrency?
Junior
It means that coroutines are launched in a specific scope and are tied to its lifecycle. When the scope is destroyed, all coroutines inside it are also destroyed.
Mid
It is a mechanism where the lifetime of a coroutine is tied to a specific CoroutineScope. This ensures that when a scope is cancelled, all its children are cancelled, and it prevents leaks by managing the hierarchy of Job objects.
Senior
It is three guarantees from the Job tree: cancelling a parent cancels its children, a parent completes only after all its children complete, and a child's failure is reported to its parent rather than lost. That is why coroutineScope can return a result or throw one exception for a whole group of parallel calls. It breaks when code leaves the tree: GlobalScope, a scope created and never cancelled, or launch(Job()), which gives the coroutine a new parent. In code review I check that every coroutine is started from a scope with a clear owner.
Learn it: Structured concurrency and cancellation
What is the difference between Job and SupervisorJob?
Junior
With a Job, one failing child cancels all its siblings. With a SupervisorJob, the other children keep running.
Mid
With a regular Job, a failing child cancels its parent, which cancels the other children, and the failure keeps moving up. With a SupervisorJob, a child failure stays in that child. Cancellation from the parent goes down to all children in both cases.
Senior
Supervision changes only how child failures travel, and only for direct children. Because the parent no longer handles the failure, a failed launch child goes to the CoroutineExceptionHandler in its context or to the uncaught exception handler, which crashes an Android app; a failed async child keeps the exception until await(). The classic bug is launch(SupervisorJob()) { launch { } ; launch { } }: the SupervisorJob becomes the parent of the outer coroutine, the inner children still use regular rules, and the outer coroutine is no longer cancelled with the scope. Use supervisorScope, or build the scope itself with SupervisorJob(), as viewModelScope does.
Learn it: Structured concurrency and cancellation
How do you make a long-running loop cancellable?
Junior
Check isActive in the loop condition, or call ensureActive() inside the loop.
Mid
If the loop calls a suspend function like delay, it is already cancellable there. A loop that only computes must check: ensureActive() throws CancellationException, isActive lets you exit the loop and return normally, and yield() checks and also lets other coroutines on the same dispatcher run.
Senior
I check once per chunk of work, not on every tiny step, so the check is cheap. Blocking calls are a separate problem: Thread.sleep or a blocking read do not see coroutine cancellation at all. For those, runInterruptible interrupts the thread on cancellation, if the call responds to interrupts, or I use a suspend API instead. After the loop I use finally for cleanup, with withContext(NonCancellable) if the cleanup suspends.
Learn it: Structured concurrency and cancellation
What happens if you catch an exception in a coroutine?
Junior
The exception stops there and the coroutine carries on from the catch block.
Mid
A catch for Exception or Throwable also catches CancellationException. If you do not rethrow it, your code keeps running after the coroutine was cancelled, until the next cancellable suspend call throws again.
Senior
Cancellation goes down the tree by cancelling Jobs; it does not depend on the exception reaching the parent. So swallowing CancellationException does not stop siblings from being cancelled. What it breaks is the cancelled coroutine itself: code after the catch runs as a zombie and can write stale state, and the parent cannot complete until that child finishes. I catch specific exceptions, or rethrow CancellationException first, or call ensureActive() in the catch.
Learn it: Structured concurrency and cancellation
What happens to a parent coroutine if one of its children fails with an exception?
Junior
With a normal Job, the parent is cancelled too, its other children are cancelled, and the exception goes further up.
Mid
The parent cancels all its other children, waits for them to finish, and then fails with the same exception, which it reports to its own parent. This continues until it reaches a root coroutine, a supervisor, or a coroutineScope or withContext, which rethrows it to the calling code. If the parent is a supervisor, only the failed child is affected.
Senior
At the top, the builder decides what happens. A root launch, or a launch that is a direct child of a supervisor, passes the exception to the CoroutineExceptionHandler in its context or, without one, to the thread's uncaught exception handler, which crashes an Android app. A root async keeps it until await(). If several children fail at once, the first exception wins and the others are attached as suppressed exceptions. So I handle expected errors with try/catch where they happen, keep coroutineScope boundaries where a group should fail together, and treat the handler as a last-resort logger.
Learn it: Exception handling in coroutines
What is the difference between coroutineScope and supervisorScope?
Junior
In coroutineScope, one failing child cancels the others. In supervisorScope, children can fail on their own.
Mid
In coroutineScope, a child failure cancels the siblings and coroutineScope rethrows the exception to the caller. In supervisorScope, a child failure does not affect the siblings or the scope, so each child has to handle its own errors. Both still wait for all children, and both rethrow if their own block throws.
Senior
coroutineScope is for splitting one task into parallel parts that succeed or fail together, and its rethrow gives you one place to catch. supervisorScope is for independent tasks, and moves error handling into each child: a failed launch child goes to a CoroutineExceptionHandler in its context or crashes the app, and an async child keeps its error until await(). In practice I use supervisorScope with async and wrap each await() in try/catch, so the UI can show partial results.
Learn it: Exception handling in coroutines
Why should you rethrow CancellationException?
Junior
Because it means the coroutine was cancelled, and catching it lets your code keep running when it should stop.
Mid
The Job is already cancelled, so swallowing the exception does not undo that. Your code carries on after the catch, maybe writing state or showing an error for a cancelled request, until the next cancellable suspend call throws again. Catch specific exceptions, or rethrow CancellationException before a generic catch.
Senior
CancellationException is the only exception the coroutine machinery treats as normal completion: it does not cancel the parent and never reaches a handler. Swallowing it creates zombie code. Throwing it on purpose to report a real error hides that error. With runCatching I rethrow it with something like onFailure { if (it is CancellationException) throw it }, or I avoid runCatching in suspend code. A TimeoutCancellationException from withTimeout is one I may catch on purpose, right around the withTimeout call, or I use withTimeoutOrNull.
Learn it: Exception handling in coroutines
How does async handle exceptions differently than launch?
Junior
An exception in launch is reported straight away and can crash the app. async keeps it in the Deferred until you call await().
Mid
That difference only matters at the top of the tree. As a child of a regular Job, both builders report the failure to the parent straight away, and the parent cancels the other children. As a root or a supervisor child, launch sends it to the exception handler, while async stores it and await() rethrows it.
Senior
This is why CoroutineExceptionHandler never applies to async: its exception has an owner, whoever calls await(). The risk is a root or supervised async whose Deferred is never awaited, because its error disappears. Another trap is viewModelScope.async { } with the await() in a different coroutine: viewModelScope uses a SupervisorJob, so the failure only shows up at await(). I keep async inside coroutineScope or supervisorScope and await every Deferred in the same block.
Learn it: Exception handling in coroutines
What is the difference between a cold stream and a hot stream?
Junior
A cold stream only starts producing data when someone starts collecting it. A hot stream produces data even if no one is listening.
Mid
A cold flow runs its producer once per collector, inside the collector's coroutine, and stops when that collector stops. A hot flow such as StateFlow or SharedFlow is active independently of collectors: values are produced whether anyone listens, and all collectors share them.
Senior
The practical differences are what a late collector sees and who owns the work. A cold flow gives every collector the full sequence from the start. A SharedFlow gives only new values plus whatever its replay keeps, and a StateFlow gives the current value and then changes, conflating fast updates. A hot flow's producer lives in a scope you choose, which is how stateIn(viewModelScope, WhileSubscribed(5_000), initial) lets a screen share one database query or network call across collectors and through rotation. Repositories usually expose cold flows, and the ViewModel decides where to share them.
Learn it: Flow basics: cold streams
If I collect a cold flow twice, how many times does the code inside the flow { ... } block run?
Junior
Twice, once for each collector.
Mid
Twice. Each collect starts a new, independent run of the producer from the beginning, even if the two collections overlap in time.
Senior
Twice, and that includes any side effects in it, like a network request or an analytics event. That is why exposing flow { emit(api.load()) } to a screen with two collectors doubles the requests. If the work should happen once, I share it with stateIn or shareIn. If each collector really needs its own run, as with a fresh Room query per screen, cold is correct.
Learn it: Flow basics: cold streams
How do you ensure a flow performs its work on a background thread?
Junior
Add flowOn(Dispatchers.IO) after the flow, so the producer runs on IO.
Mid
flowOn changes the context of the upstream: the builder and every operator above it. The collector keeps its own context. Do not use withContext around emit inside flow { }; that breaks context preservation and throws IllegalStateException.
Senior
I put flowOn in the data layer, so collectors can use the flow from the main thread. Only the operators above each flowOn are affected, so a map placed after it runs on the collector's dispatcher. When the dispatcher changes, flowOn runs the upstream in a separate coroutine with a buffer between the two sides, so the producer can run ahead of a slow collector. For flows that are already main-safe, like Room or a callbackFlow from a library, I add no flowOn. For a blocking producer I inject the dispatcher so tests can replace it.
Learn it: Flow basics: cold streams
What happens to a cold flow if the coroutine collecting it is cancelled?
Junior
The producer stops too, because it runs in the collector's coroutine.
Mid
Cancellation reaches the producer at its next cancellable suspension point, such as delay or emit in the flow builder, and a CancellationException ends the flow. Cleanup belongs in try / finally inside the flow, or in onCompletion.
Senior
The flow { } builder checks for cancellation on every emit, but some flows do not: (1..1_000_000).asFlow() has no checks, so a collector without suspension points runs to the end even after cancellation. Adding .cancellable() fixes that. For a callback-based source, callbackFlow with awaitClose is what unregisters the listener when the collector is cancelled. Cleanup in finally that needs to suspend goes in withContext(NonCancellable).
Learn it: Flow basics: cold streams
When would you choose StateFlow over SharedFlow, and vice versa?
Junior
StateFlow is for state that always has a current value, like the selected item or a loading flag. SharedFlow is for values that should be broadcast to whoever is listening right now, without an initial value and without a new collector necessarily seeing the last one.
Mid
StateFlow keeps the latest value, gives it to every new collector, is conflated and skips equal values, which is exactly what UI state needs. SharedFlow with replay = 0 delivers each value only to collectors that are subscribed at that moment. A common pitfall is using it for one-off UI events: if the screen is not collecting, for example during rotation, the event is silently lost.
Senior
StateFlow is roughly a SharedFlow with replay = 1, onBufferOverflow = DROP_OLDEST, an initial value and equality-based skipping. I use SharedFlow (often via shareIn) when several collectors must see a stream of values, like a broadcast of connection changes. For one-off UI events I follow the architecture guidance and put them in state that the UI clears after handling, or use a Channel when there is exactly one consumer. In reviews I look for MutableSharedFlow used as an event bus to a single screen and ask what happens when nobody is collecting.
Learn it: StateFlow and SharedFlow
Explain what SharingStarted.WhileSubscribed(5_000) does and why the 5-second window exists.
Junior
It starts the upstream flow when the first subscriber arrives and stops it 5 seconds after the last subscriber leaves. The 5 seconds is a grace period so a configuration change such as rotation does not stop and restart the upstream.
Mid
stateIn launches a sharing coroutine in the given scope and watches subscriptionCount. With WhileSubscribed, when the count drops to zero it waits stopTimeoutMillis; if a subscriber returns in time, nothing is restarted. During rotation the old UI unsubscribes and the new one subscribes within a fraction of a second, so the upstream keeps running. In the background the UI stops collecting, and after 5 s the upstream, say a location or database flow, is cancelled. Eagerly and Lazily never stop it.
Senior
WhileSubscribed has a second parameter, replayExpirationMillis, which defaults to Long.MAX_VALUE: after the upstream stops, the StateFlow keeps its last value, so when the user returns they see that value until the restarted upstream emits a fresh one. Setting it to 0 resets to the initial value instead. The timeout is a trade-off: too short and rotations restart expensive work, too long and background work continues. I verify it with runTest by cancelling the collector, advancing virtual time past the timeout, and checking that the upstream completed.
Learn it: StateFlow and SharedFlow
What is the difference between emit and tryEmit on a MutableSharedFlow?
Junior
emit is a suspending function that can wait when the buffer is full. tryEmit is a regular function that returns true if the value was accepted and false if it would have had to wait.
Mid
emit suspends only when there are subscribers and the buffer is full because one of them is slow; it resumes when space frees up. tryEmit never suspends and returns false in that case. With no subscribers, both return immediately and the value is dropped, apart from the replay cache, and tryEmit still returns true. With the default MutableSharedFlow(), tryEmit returns false whenever someone is collecting, because there is no buffer.
Senior
The buffer is replay plus extraBufferCapacity, and onBufferOverflow decides what happens when it is full: SUSPEND (the default), DROP_OLDEST or DROP_LATEST. With a DROP option, emit never suspends and tryEmit always succeeds. If tryEmit is needed from a non-suspending callback, I give the flow extraBufferCapacity or a drop policy so it cannot fail silently. None of this makes a SharedFlow deliver to collectors that are not subscribed yet; for that you need state or a Channel.
Learn it: StateFlow and SharedFlow
How do you collect a StateFlow and a SharedFlow in a Compose screen without collecting in the wrong lifecycle state?
Junior
For StateFlow, use collectAsStateWithLifecycle(), which gives a State that Compose reads. For a stream of events, collect inside a LaunchedEffect.
Mid
collectAsStateWithLifecycle() collects only while the lifecycle is at least STARTED and stops when the app goes to the background. A plain LaunchedEffect with collect keeps collecting while the screen is stopped, because the composition stays alive in the background. For event streams, use LaunchedEffect(lifecycleOwner) with lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) inside, so collection stops and restarts with the lifecycle.
Senior
Stopping collection has a consequence for SharedFlow: with replay = 0, events emitted while the screen is stopped are lost, because there is no subscriber. That is acceptable for a broadcast but not for a navigation or error event, which is why those belong in state or a Channel. collectAsState without the lifecycle variant keeps the upstream of a WhileSubscribed stateIn alive in the background, defeating the timeout. In code review I flag LaunchedEffect(Unit) with a bare collect on a ViewModel flow.
Learn it: StateFlow and SharedFlow
What is the difference between map and mapLatest?
Junior
map transforms every value. mapLatest cancels the previous transformation if a new value arrives before it finishes.
Mid
map runs its suspending block for each value in turn; the next value waits until the current block returns, and nothing is cancelled. mapLatest runs the block for each value in a new coroutine and cancels the one still running when a new value arrives. It fits expensive work where only the result for the latest input matters, like a search.
Senior
mapLatest is built on transformLatest, which collects upstream in a channel-based flow and launches each transform as a child coroutine, cancelling and joining the previous child first. Cancellation is cooperative, so a transform stuck in blocking code is not stopped early. It adds a buffer between producer and collector, and it is still marked ExperimentalCoroutinesApi. Also, cancelling the coroutine does not undo side effects already done, like a request already sent, which is why it is usually combined with debounce.
Learn it: Flow operators
How does flowOn work?
Junior
It changes which thread the upstream part of the flow runs on.
Mid
It changes the CoroutineContext, usually the dispatcher, for the operators above it, up to the previous flowOn. It does not affect the collector's context, so the collector can stay on the main thread while the producer runs on IO.
Senior
When the dispatcher changes, flowOn runs the upstream in a separate coroutine and passes values to the collector through a channel, so it behaves like a buffer and fuses with an adjacent buffer call. This is the supported way to change context: calling emit from inside withContext in a flow builder breaks context preservation and throws an IllegalStateException. It only shifts the upstream, so you place it right below the heavy part of the chain.
Learn it: Flow operators
What is the difference between flatMapMerge and flatMapLatest?
Junior
flatMapMerge runs all the inner flows at once. flatMapLatest only keeps the newest one running.
Mid
flatMapMerge collects several inner flows concurrently and merges their emissions, so results can arrive out of order. flatMapLatest cancels the previous inner flow as soon as the upstream emits a new value. flatMapConcat is the third option: it collects inner flows one after another.
Senior
flatMapMerge has a concurrency parameter, by default DEFAULT_CONCURRENCY, which is 16. It suits independent work where every result matters, like uploading several files. flatMapLatest is a switching operator: the inner flow for the old key is cancelled, so its emissions can never reach the UI after the key changes. That makes it the default for UI state derived from a changing key, such as a query or a selected id.
Learn it: Flow operators
How do you handle errors in a Flow?
Junior
Use the catch operator in the chain, or a try-catch around the collect call.
Mid
The catch operator handles exceptions from upstream and can emit a fallback value. After catch runs, the flow completes. Exceptions thrown inside collect are not caught by it, so those need a try-catch or should be moved into onEach before catch.
Senior
catch is transparent to downstream: it only sees upstream errors, which keeps exception transparency. Because the flow completes after it, placement matters: in a long-lived stream I put catch on the inner flow of flatMapLatest so one failed request does not end the stream, or use retryWhen for transient failures. catch does not handle cancellation of the collecting coroutine, and any hand-written try-catch or runCatching must rethrow CancellationException.
Learn it: Flow operators
How do you collect a Flow in an Android Activity safely?
Junior
Inside lifecycleScope.launch I call repeatOnLifecycle(Lifecycle.State.STARTED) and collect in its block, so collection only runs while the Activity is visible.
Mid
I start it in onCreate: lifecycleScope.launch, then repeatOnLifecycle(STARTED), then one launch per flow inside the block, because a StateFlow collect never returns. In a Fragment I use viewLifecycleOwner for both the scope and repeatOnLifecycle. For a single flow, flowWithLifecycle does the same thing.
Senior
repeatOnLifecycle launches the block when the lifecycle reaches STARTED and cancels it when it drops below, so the subscription really ends. That matters upstream: a stateIn with WhileSubscribed(5_000) stops 5 s later, and a callbackFlow runs awaitClose and unregisters its listener. launchWhenStarted only suspended the coroutine, so the subscription and producer stayed alive, which is why it was deprecated. repeatOnLifecycle itself suspends until DESTROYED, so nothing should follow it in the same coroutine.
Learn it: Collecting flows safely in the UI
What is the difference between lifecycleScope.launch and repeatOnLifecycle?
Junior
lifecycleScope.launch runs until the Activity is destroyed, while repeatOnLifecycle runs its block only while the screen is at least in the given state.
Mid
lifecycleScope.launch keeps the coroutine active until the lifecycle is destroyed. repeatOnLifecycle cancels its block when the lifecycle leaves the given state, for example STARTED to CREATED at onStop, and launches it again when the state is reached again.
Senior
lifecycleScope is cancelled only at DESTROYED, so it ignores visibility. repeatOnLifecycle is a suspend extension on LifecycleOwner and Lifecycle that observes lifecycle events and runs the block in a fresh child coroutine on each entry to the state. Each restart re-collects: a StateFlow gives its current value immediately, a cold flow starts from the beginning. lifecycleScope.launch is still right for one-off work that should finish even when the screen goes to the background, as long as it is screen-scoped.
Learn it: Collecting flows safely in the UI
Why is it a bad idea to collect flows while the app is in the background?
Junior
It wastes battery and data, and updating the UI at the wrong time can crash the app.
Mid
Values keep being produced and processed although the user cannot see them, which costs CPU, network and battery. It can also cause an IllegalStateException if the collector commits a Fragment transaction after onSaveInstanceState.
Senior
The biggest cost is usually upstream, not in the collector: as long as the UI is subscribed, a WhileSubscribed stateIn keeps its database query, location updates or polling running. Stopping collection at onStop lets the whole chain shut down, and the StateFlow still holds the last value for when the user returns. The other risk is doing UI work like navigation or Fragment transactions in a state where the platform forbids it.
Learn it: Collecting flows safely in the UI
How would you handle flow collection in Jetpack Compose?
Junior
I use collectAsStateWithLifecycle() to turn the flow into a State that the composable reads.
Mid
collectAsStateWithLifecycle() collects only while the lifecycle is at least STARTED, unlike collectAsState(), which keeps collecting while the app is in the background because the composition stays alive. For a StateFlow it uses the current value as the initial state.
Senior
collectAsStateWithLifecycle is built on produceState plus lifecycle.repeatOnLifecycle(minActiveState), so it stops when the composable leaves the composition or the lifecycle drops below minActiveState, which defaults to STARTED. It uses LocalLifecycleOwner by default, so inside a navigation destination it follows that destination's lifecycle. For events that must not be missed I prefer modelling them as state rather than collecting a SharedFlow, since stopped collection means no subscriber.
Learn it: Collecting flows safely in the UI

State and architecture

Why do you expose StateFlow instead of MutableStateFlow from a ViewModel?
Junior
StateFlow is read-only, so the UI can collect it but cannot change the value. With MutableStateFlow the UI could set value or call update and bypass the ViewModel.
Mid
It enforces a one-way contract: the ViewModel is the only writer. If a Fragment or Composable can write to the flow, its writes race with the ViewModel's own coroutines, for example a load that finishes later and overwrites the change, and every collector sees the write immediately. Keeping the MutableStateFlow private and returning asStateFlow() prevents that.
Senior
With a single writer, every state transition is a ViewModel method, so you can unit-test each one by calling it and asserting on the StateFlow, with no UI, and you can find every change by reading one class. asStateFlow() returns a read-only wrapper, so the UI cannot even cast it back to MutableStateFlow. In a large codebase a custom lint or detekt rule that flags public MutableStateFlow properties keeps the rule enforced.
Learn it: ViewModel and UI state
When would you choose a sealed class over a flat data class for UI state?
Junior
A flat data class is fine when you have a few fields like isLoading and error. A sealed type is better when the states are mutually exclusive, like Loading, Success and Error, because a when expression must handle every case.
Mid
The trade-off is boilerplate versus safety. A flat data class with nullable fields can hold contradictory values, for example isLoading true and error non-null at the same time, and nothing stops you. A sealed hierarchy makes that impossible. The cost is that independent sub-states, like a form field and a list, are awkward inside one sealed type, and switching branches loses data, such as the old list while reloading.
Senior
I often combine them: a data class for things that exist independently, like the query, filters and a pending message, with a sealed content field for the mutually exclusive part, such as Loading, Loaded(items) or Failed(reason). That keeps impossible combinations out without losing the query when content goes back to Loading. A sealed type also gives a finite set of cases to cover in tests. In an MVI setup the reducer is usually cleaner when each intent maps to a small copy of one data class.
Learn it: ViewModel and UI state
How does stateIn with WhileSubscribed work, and why does the timeout matter?
Junior
stateIn converts a cold Flow into a hot StateFlow so several collectors share one upstream. WhileSubscribed starts the upstream when the first collector subscribes and stops it some time after the last one leaves. The timeout is that delay.
Mid
The default timeout is 0, so the upstream stops as soon as the last collector leaves. On rotation the old UI unsubscribes before the new one subscribes, so the database query or network call restarts every time. With WhileSubscribed(5_000) the new UI subscribes within the 5 s and the upstream keeps running. Either way, the StateFlow keeps its last value, so the new UI sees data immediately.
Senior
The sharing coroutine runs in the scope you pass, usually viewModelScope, so it always ends when the ViewModel is cleared; the timeout decides when it stops earlier, while the ViewModel is alive but nobody is collecting, for example in the background. WhileSubscribed also has replayExpirationMillis, which defaults to keeping the last value forever; setting it to 0 resets the StateFlow to its initial value when sharing stops. All of this only works if the UI collects with repeatOnLifecycle or collectAsStateWithLifecycle; otherwise the subscriber never leaves.
Learn it: ViewModel and UI state
How do you handle a one-off event like showing a snackbar without losing it or showing it twice?
Junior
I put the message in the UI state as a nullable field. The UI shows it and then tells the ViewModel it was shown, and the ViewModel sets it back to null.
Mid
A SharedFlow with replay 0 drops the event if nobody is collecting, for example during a rotation or while the app is in the background. A Channel exposed with receiveAsFlow keeps the event until it is received, which is better, but an event can still be lost if the collector is cancelled after receiving it and before handling it. A nullable field in state survives rotation, and because the UI explicitly clears it, it is shown once.
Senior
The state approach is what the Android architecture guide recommends, and it is easy to test: assert the field is set after the action and null after onMessageShown(). For several messages, keep a list in state and remove each one as it is shown. If a team uses a Channel, I check that it is collected with repeatOnLifecycle on Dispatchers.Main.immediate, which narrows the loss window, and that there is only one collector, because a Channel delivers each event to one receiver only.
Learn it: ViewModel and UI state
What is unidirectional data flow and why does it matter?
Junior
Events go up from the UI to the ViewModel, and state goes back down to the UI. The UI only renders state and emits events; it never changes state directly. This makes the data path easy to follow.
Mid
The state is a pure function of all past events, so the same event sequence always produces the same state. In Android this means a StateFlow<UiState> that the UI collects and a single onEvent entry point. The usual pitfall is letting a second coroutine or the UI itself write to the same flow, which breaks the invariant.
Senior
The trade-off is indirection: every change, even a small one, goes through the ViewModel, which can feel heavy on a simple screen. In review I check that no MutableStateFlow escapes the ViewModel, that every write uses update, that the UI only calls ViewModel methods and never holds its own copy of business state, and that the UI collects with collectAsStateWithLifecycle or repeatOnLifecycle. Purely visual state, such as whether a dropdown is expanded, can stay in the UI; UDF is about who owns each piece of state, not about moving everything into the ViewModel.
Learn it: Unidirectional data flow
How do you handle one-off events like navigation or a toast in UDF?
Junior
The ViewModel puts the result in the UI state, for example a userMessage: String? field. The UI shows it and then calls a method like onMessageShown(), and the ViewModel sets the field back to null.
Mid
Google's guidance is that events coming from the ViewModel should become UI state. A SharedFlow with replay 0 drops an event while nobody collects, for example during rotation. With replay 1 it replays the old event to the new collector, so it fires twice. A Channel buffers events, but one can still be lost if the collector receives it and is cancelled before acting on it. A state field the UI clears is not lost and not repeated.
Senior
The state field survives rotation because the ViewModel does. It survives process death only if you also save it through SavedStateHandle; a Channel never does. Events that start in the UI and need no business logic, like tapping a Help button, do not go through the ViewModel at all: the UI navigates directly. For several messages I keep a list in state and remove each one by id after it is shown. I test it as plain state: after the action the field is set, after the acknowledgement it is null.
Learn it: Unidirectional data flow
MVVM versus MVI: when would you choose one over the other?
Junior
MVVM has a ViewModel with state and a few command methods. MVI has a single state, a list of intents, and a reducer. MVI is more structured and testable.
Mid
MVI forces all logic through one pure reducer, which is great for testing but adds boilerplate. MVVM lets the ViewModel have several methods, which is more flexible for complex screens. The cost of MVI is that every small change goes through the reducer, which can be overkill for a two-button screen.
Senior
MVI shines when many event sources (timer, network, user input, background sync) modify the same state, because every transition is visible in one reducer and easy to test; lost writes are prevented by update in either pattern. MVVM is fine when the ViewModel has a few clear methods and the state is simple. The real question is whether a pure reducer is worth the indirection. You verify by checking if the reducer is actually pure, if the state is truly a function of events, and if the number of intents has grown so large that the when in the reducer is hard to read.
Learn it: Unidirectional data flow
How do you test a ViewModel that uses UDF?
Junior
You create the ViewModel, call onEvent with a few events, and assert the value in the StateFlow. You use a fake repository that returns a fixed list.
Mid
You use runTest from kotlinx-coroutines-test, which runs delays in virtual time, and replace Dispatchers.Main with a test dispatcher via Dispatchers.setMain, because viewModelScope uses Main. You feed a sequence of events and assert intermediate states, not just the final one. The pitfall is with StandardTestDispatcher: launched work does not run until you call advanceUntilIdle or runCurrent.
Senior
Test the reducer as a pure function with no coroutines at all: feed a state and an event, assert the new state. For the ViewModel layer, use runTest, a test Main dispatcher and a fake repository, and Turbine if you want to assert every emission. For process death, construct the ViewModel with a SavedStateHandle that has pre-populated keys and assert the restored state matches. For one-off results you assert the field is set after the action and null after the UI's acknowledgement call.
Learn it: Unidirectional data flow
How do you expose UI state from a ViewModel?
Junior
The ViewModel holds a StateFlow of a data class. The UI collects that flow. The data class has fields like isLoading, items, and error. The ViewModel updates the flow when data arrives.
Mid
You wrap a MutableStateFlow privately and expose a read-only StateFlow with asStateFlow(). Every write goes through the update extension so it is atomic. In Compose the UI calls collectAsStateWithLifecycle; in a Fragment you wrap collection in repeatOnLifecycle(STARTED).
Senior
You also decide between a flat data class and a sealed interface per screen. For derived or long-running flows you use stateIn with WhileSubscribed(5_000) to avoid restarting upstream on brief collector loss. In review you check that no MutableStateFlow is public, that every write uses update, and that suspend calls are not wrapped in runCatching, which would swallow CancellationException.
Learn it: MVVM in practice
What happens if you collect a StateFlow in the wrong lifecycle scope?
Junior
If the scope outlives the view, the collection keeps running and holds a reference to the view, which causes a memory leak. The view is not garbage-collected.
Mid
In a Fragment inside a ViewPager2, collecting in lifecycleScope means the collection survives onDestroyView. The old view is retained, and when the user swipes back the new view starts a second collection, causing duplicate rendering or a crash.
Senior
The fix is viewLifecycleOwner.lifecycleScope plus repeatOnLifecycle(STARTED), or collectAsStateWithLifecycle in Compose. repeatOnLifecycle cancels the collection when the lifecycle drops below STARTED and starts it again on return, so nothing runs in the background and each view gets exactly one collector. Because StateFlow always holds the latest value, nothing is missed while stopped. You verify with LeakCanary in debug builds and audit for GlobalScope and plain lifecycleScope collection.
Learn it: MVVM in practice
MVVM vs MVI: when would you choose each?
Junior
MVVM is simpler: the ViewModel exposes state and has methods the UI calls. MVI adds a sealed intent type and a reducer that maps intents to new state. Many teams use MVVM for simple screens and MVI for complex ones.
Mid
MVI uses a single state plus intents and a pure reducer. The reducer is trivially unit-testable and gives a single log of intents for debugging. The cost is more boilerplate and an extra layer of indirection for simple CRUD screens, where a few ViewModel methods are easier to read.
Senior
Both follow unidirectional data flow with one immutable state; the difference is whether transitions live in many methods or one reducer. A reducer pays off when many inputs (user, timers, sync) change the same state and you want to test every transition as a pure function; if the team does not test it, the ceremony adds little. Async work still happens outside the reducer, and its results come back as intents. I pick one convention per codebase, or a clear rule for when each applies, and record it in an ADR so screens stay consistent.
Learn it: MVVM in practice
How do you test a ViewModel?
Junior
You create the ViewModel with a fake repository, call a function, and check the state value. You use a test dispatcher to control time.
Mid
You replace Dispatchers.Main with a test dispatcher using Dispatchers.setMain, usually in a JUnit rule, because viewModelScope uses Main. Then you use runTest, inject a fake repository, call the function, run advanceUntilIdle, and assert on state.value. For flows you collect inside runTest, often with Turbine, and assert on emitted values.
Senior
You test each state transition: loading, success, error and retry, not just the final state. You test cancellation by using a fake that never returns, cancelling the work, and asserting isLoading is reset. For SavedStateHandle you construct the ViewModel with a pre-populated handle and verify the restored state. You keep UI concerns out of the ViewModel test; that is the job of the UI test.
Learn it: MVVM in practice
What is MVI and how does it differ from MVVM?
Junior
MVI uses one immutable state object and a sealed intent class. The user action becomes an intent, and a reducer function produces the next state. In MVVM the ViewModel also exposes one state, but each user action is a separate method that updates it.
Mid
In MVI the reducer is a pure function reduce(state, intent) with no side effects. The ViewModel calls it synchronously, then launches coroutines for I/O. In MVVM the logic lives inside ViewModel methods, so testing a transition means building the ViewModel with fakes and a test dispatcher. MVI centralises transitions in one place, which makes the state machine explicit.
Senior
The real trade-off is type count versus testability. MVI adds a sealed intent and a reducer per screen; for a 10-screen app that is 10 extra sealed classes. But the reducer is a pure Kotlin function you can test with zero Android dependencies. It pays off on screens where many inputs change the same state; for a settings screen with two toggles, MVVM is less ceremony. I also check whether the team actually writes reducer tests; if not, the MVI structure is dead weight.
Learn it: MVI in practice
How do you handle one-off events in MVI?
Junior
I put them in the state, for example selectedId or userMessage. The UI acts on the field, then sends an intent like MessageShown, and the reducer sets the field back to null.
Mid
That follows Google's guidance that ViewModel events become UI state. A SharedFlow with replay 0 drops an event while nobody collects, and replay 1 repeats it after rotation. A Channel buffers events, but one can still be lost if the collector receives it and is cancelled before acting. A field the reducer clears on acknowledgement is not lost and not repeated, and both steps are reducer tests.
Senior
The field survives rotation because the ViewModel does; it survives process death only if I also save it through SavedStateHandle. For several messages I keep a list with ids and remove each one when the UI reports it shown. Events that start in the UI and need no business logic, like tapping Help, never reach the ViewModel: the UI navigates directly. Some MVI libraries expose a separate side-effect stream (Orbit side effects, MVIKotlin labels) backed by a channel-like stream; if a team uses one, I check it is collected with repeatOnLifecycle on Dispatchers.Main.immediate and has a single collector, and I accept the small loss window.
Learn it: MVI in practice
When do you need stateIn in an MVI ViewModel, and why WhileSubscribed(5_000)?
Junior
If the state is a MutableStateFlow that the reducer writes to, I expose it with asStateFlow and need no stateIn. stateIn turns a cold flow, such as a Room query, into a StateFlow the UI can collect.
Mid
A typical case is combine(_state, repository.observeItems()) { s, items -> s.copy(items = items) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState()). With a timeout of 0, a rotation stops and restarts the upstream, repeating the query. With 5_000 the new UI subscribes within the window, and the upstream still stops in the background. Either way the StateFlow keeps its last value, so the UI does not flash.
Senior
The sharing coroutine runs in viewModelScope, so it always ends at onCleared; the timeout only decides when it stops earlier. WhileSubscribed also has replayExpirationMillis, which by default keeps the last value forever. The whole thing only works if the UI collects with collectAsStateWithLifecycle or repeatOnLifecycle; otherwise the subscriber never leaves. I also pick an initialValue that means loading, so the first frame is not a misleading empty list.
Learn it: MVI in practice
How do you test a reducer?
Junior
You call reduce(knownState, knownIntent) and assert the returned state equals the expected state. No Android runtime, no coroutines, no mocks needed.
Mid
Because the reducer is pure, you can write a table-driven test: a list of (inputState, intent, expectedState) triples. This covers every branch of the when without a test framework beyond JUnit. The pitfall is forgetting to test the 'no-op' case where an intent does not change the state (e.g., Select when the item is already selected).
Senior
In a real codebase I check three things: (1) the reducer is a top-level function or an object method, not a method on the ViewModel, so it has no hidden dependencies; (2) the test file has a case for every branch of the when, and the when has no else, so new intents force new cases; (3) the test does not use runTest or Dispatchers.Main, because a pure reducer should not need a coroutine. If the reducer is a suspend function or touches a repository, it is not pure and the test is testing the wrong thing. I also look for property-based tests (e.g., 'reducing with a no-op intent returns the same state') to catch copy-paste errors in the when.
Learn it: MVI in practice
What is the difference between a configuration change and process death?
Junior
A configuration change like rotating the screen recreates the Activity but keeps the ViewModel. Process death happens when the system kills the app in the background to free memory, and the ViewModel and everything else in memory is gone.
Mid
On a configuration change the Activity is destroyed and recreated in the same process, and the ViewModelStore is kept, so the same ViewModel instance is reused. On process death the whole process is killed; when the user returns, a new process starts, the Activity is recreated from its saved-state Bundle, and a new ViewModel is created. Only what was in saved state, such as SavedStateHandle and rememberSaveable, comes back.
Senior
After process death the system restores the task and the top Activity with its saved state, so the user may land on a deep screen with Application.onCreate just run and every singleton and cache empty. Saved state is restored only for system-initiated death; if the user swiped the app away or finished the screen it is discarded. So I design each screen to rebuild from its small saved inputs, like ids and the query, plus persistent storage, and I test it with adb shell am kill rather than rotation.
Learn it: SavedStateHandle and process death
How do you prevent TransactionTooLargeException when using SavedStateHandle?
Junior
Don't put too much data in it. Only put small things like IDs or short strings.
Mid
Avoid storing large objects, lists of loaded data or bitmaps. Store small identifiers and user input, and reload the rest from a database or the network.
Senior
SavedStateHandle contents go into the saved-state Bundle, which is sent to the system through Binder when the app is stopped. The Binder transaction buffer is about 1 MB and is shared by all transactions in progress in the process, so the safe size is far below that. The saved state of every Fragment, every view and every rememberSaveable on the screen adds to the same Bundle. I keep only ids and inputs there and measure the size per screen with a tool like TooLargeTool in debug builds.
Learn it: SavedStateHandle and process death
How would you test that your ViewModel correctly handles process death?
Junior
I write a unit test that creates the ViewModel with a SavedStateHandle that already contains values, and check that the state uses them.
Mid
I create a unit test where I pass SavedStateHandle(mapOf(...)) with the values that would have been saved into the ViewModel constructor, and assert that the UI state reflects them and that the data is reloaded from the fake repository.
Senior
In unit tests I do a round trip: drive the first ViewModel, copy the keys it wrote from its handle into a new SavedStateHandle, build a second ViewModel from it and assert the screen is restored. For Compose UI state I use StateRestorationTester to check rememberSaveable. On a device I background the app and run adb shell am kill, because rotation and ActivityScenario.recreate keep the ViewModel and so never test this path.
Learn it: SavedStateHandle and process death
Why should we use getStateFlow instead of just updating a MutableStateFlow?
Junior
With getStateFlow the value is stored in the SavedStateHandle, so it comes back after process death. A plain MutableStateFlow is lost.
Mid
getStateFlow returns a StateFlow that reads from the SavedStateHandle and updates whenever you set that key. If you use a separate MutableStateFlow, you have to write to both the flow and the handle every time, which is easy to forget.
Senior
getStateFlow makes the handle the single source of truth: the StateFlow is read-only, every write goes through savedStateHandle[key] = value, and the restored value is the flow's starting value after process death. The value must still be a Bundle type and small. I usually derive the rest of the UI state from these saved inputs with operators like mapLatest or combine and stateIn, so restoring a few keys is enough to rebuild the whole screen.
Learn it: SavedStateHandle and process death
How do you handle one-off events like toasts or navigation in MVVM?
Junior
You add a nullable field to the UiState data class, such as userMessage. The UI collects the state, sees the field is non-null, shows the message, and then calls a function on the ViewModel that sets the field back to null.
Mid
Google's guidance is that events from the ViewModel should become UI state. StateFlow gives its latest value to every new collector, so the field must be cleared by the UI after acting, typically at the end of a LaunchedEffect keyed on the event. For navigation you often model the outcome, like isUserLoggedIn or placedOrderId, and the UI navigates when it sees it. Events that start in the UI and need no business logic, like tapping Help, are handled in the UI directly.
Senior
A single nullable field holds one event; if two arrive before the UI acts, the first is overwritten. When that matters I keep a list of messages with ids and remove each one by id after it is shown. The field survives rotation because the ViewModel does, and survives process death only if I also save it with SavedStateHandle. I test it as plain state: set after the action, null after the acknowledgement, and for the list case, both messages delivered in order.
Learn it: One-off events done right
When would you choose a Channel over a state field for one-off events?
Junior
Google recommends the state field for events coming from the ViewModel. A Channel delivers each event once to a single collector, so some teams use it for navigation, but it can still lose an event.
Mid
A Channel buffers events while nobody collects, so the gap during rotation is not the problem. The loss happens when the collector has already received an event and is cancelled before acting on it, for example when the event is sent from a background thread and the lifecycle stops before the collector resumes on the main thread. A state field has no such window and is easier to test.
Senior
I default to state. If a codebase already uses a Channel, I check that there is exactly one collector, that it runs inside repeatOnLifecycle(STARTED) on Dispatchers.Main.immediate, and that events are sent from the main thread, which narrows the loss window. I accept the remaining risk only for events where a rare loss is harmless, never for something like navigating after a payment. Some teams use onUndeliveredElement to detect lost elements, but that is a workaround, not a fix.
Learn it: One-off events done right
What is the difference between SharedFlow with replay = 0 and a Channel for one-off events?
Junior
Both deliver events without keeping them as state. SharedFlow is a hot Flow that broadcasts to all collectors. A Channel is a queue that you expose as a Flow with receiveAsFlow, and each event goes to one collector.
Mid
With no subscribers, a SharedFlow with replay 0 drops the event: emit returns immediately and nothing is stored. A Channel keeps the event in its buffer, or suspends the sender, until someone receives it. With two collectors, SharedFlow delivers every event to both, so it can show a snackbar twice; a Channel splits events between them.
Senior
So SharedFlow replay 0 loses events in exactly the moments that matter, rotation and background, and a Channel loses them only in the short window after receive. With the default zero buffer, tryEmit returns false and drops the event whenever there are subscribers, so code that uses tryEmit needs extraBufferCapacity. Neither survives process death. That is why Google recommends state: it removes both failure modes, and the acknowledgement call makes delivery explicit and testable.
Learn it: One-off events done right
How do you test a one-off event in a ViewModel?
Junior
You call the action function on the ViewModel and assert that the event field in state.value is set. Then you call consumeEvent and assert the field is null.
Mid
You use runTest with a test Main dispatcher and a fake repository, trigger the action, run advanceUntilIdle, and assert the event appears in state. The pitfall is stopping there: if you never assert the cleared state, a missing consume call still passes. Assert both steps.
Senior
For MVI I test the reducer directly: the result intent sets the field, the acknowledgement intent clears it. For MVVM I test the ViewModel the same way, plus the queue case: two events before any acknowledgement, both delivered in order, and an acknowledged id never returns. If the team uses a Channel, I collect it with Turbine and also test the cancelled-collector case, which usually shows why state is simpler.
Learn it: One-off events done right

Data

What happens when a DAO method returns a Flow?
Junior
The Flow emits the current query result when you collect it, and emits again whenever the table changes, so the UI stays up to date without calling the DAO again. The query runs off the main thread.
Mid
Room tracks which tables the query reads. After a write transaction on any of those tables commits, Room runs the query again and emits the new result. The granularity is the table: an update to a row the WHERE clause excludes, or one that writes identical data, still produces an emission, so I add distinctUntilChanged() when that matters. The Flow is cold: the query runs per collector, and only while it is collected.
Senior
Under the hood the InvalidationTracker installs SQLite triggers on observed tables that record changes in a tracking table. When a transaction ends, Room checks that table and notifies observers of the changed tables, and the Flow re-queries on Room's executor. Consequences: writes made outside Room's connection, or from another process, are not seen unless you enable multi-instance invalidation; a Flow over a hot table can re-query many times a second, so I keep queries narrow in columns and add distinctUntilChanged or conflate; and a @Relation query also observes its child tables. I test it with an in-memory database and Turbine.
Learn it: Room: entities, DAOs, queries
What is @Upsert and when would you choose it over @Insert?
Junior
@Upsert inserts a row if its primary key is new and updates it if the key already exists. It is the usual choice for saving data from the server, because the same item arrives again on every refresh.
Mid
The alternative people used before was @Insert(onConflict = REPLACE). REPLACE deletes the conflicting row and inserts a new one, so a foreign key with ON DELETE CASCADE deletes that row's children. @Upsert tries the insert and, on a primary-key conflict, updates the existing row, so children survive. If an existing row should win, for example a local edit, I use @Insert(onConflict = IGNORE) instead.
Senior
Upsert replaces every column of the row, so a refresh can still overwrite local-only state, such as a pendingSync flag or a draft field. For that I either keep local state in a separate table, use a partial @Update with a smaller class, or write a @Query UPDATE for only the server columns, and I skip rows with unsynced edits inside one transaction. I also watch non-primary unique indexes: Upsert's update matches rows by primary key, so a conflict on another unique column does not update the row you expected. The server key should be the primary key.
Learn it: Room: entities, DAOs, queries
How does Room handle types that SQLite does not support natively?
Junior
You write @TypeConverter functions that turn your type into one SQLite supports, like Instant to Long, and back. You register the class with @TypeConverters on the database.
Mid
Registration can be on the database, an entity, a DAO or a single field; the narrower the scope, the fewer places it applies. If no converter matches a column type, KSP fails the build. Enums need no converter because Room stores them by name, which means renaming or removing an enum constant breaks reading old rows unless a migration rewrites them.
Senior
I keep converters for value types, not for object graphs: storing a list as a JSON string works but cannot be queried, indexed or constrained, so a one-to-many relation usually deserves its own table with a foreign key and a @Relation. For enums and sealed types I store a stable code I control rather than the class or constant name, so a refactor cannot change the stored value. Converters run on every read and write, so I keep them cheap and pure, and I test round-trips.
Learn it: Room: entities, DAOs, queries
How do you make several writes atomic in Room?
Junior
You put them in one transaction, either with a @Transaction DAO method or with db.withTransaction in the repository. If something throws inside, every write in the block is rolled back.
Mid
Each DAO call is its own transaction otherwise, so a crash between two calls leaves partial data. withTransaction is handy when the writes span several DAOs. Flow observers are notified once, after the transaction commits, so the UI never sees the half-written state.
Senior
Keep the transaction short and only do database work inside it: no network calls, because the connection is held for the whole block and other writes wait. withTransaction is a suspend function and is re-entrant, so nested calls join the outer transaction. I also mark @Relation reads @Transaction, because Room runs several queries for them. For tests I make the second DAO throw on an in-memory database and assert nothing was committed.
Learn it: Room: entities, DAOs, queries
What happens when you bump the @Database version but do not provide a migration?
Junior
Users who upgrade crash. When the database is opened, Room sees that the file's version is older than the one in the annotation and looks for a migration. If it finds none, it throws IllegalStateException saying a migration was required but not found. Fresh installs are fine, which is why it is easy to miss.
Mid
It happens the first time the database is opened, usually the first query, not at build(). Room needs a path covering every step: going from 3 to 5 with only Migration(3, 4) still crashes, unless there is a direct 3 to 5 migration. Auto-migrations listed in @Database count as steps. If a destructive fallback is configured, Room drops and recreates the tables instead of crashing.
Senior
After running the path Room validates the schema against what the entities expect, so a migration that runs but produces a different column type, nullability or default also throws. I protect against both in CI: MigrationTestHelper creates the database at each shipped version and runs runMigrationsAndValidate to the current one, and a review rule ties changes in the schemas folder to a migration and a test. In production, this crash blocks every upgrading user, so a staged rollout watching crash rate is the last line of defence.
Learn it: Room migrations
Explain the difference between auto-migration and a manual Migration.
Junior
An auto-migration is declared in @Database with AutoMigration(from, to), and Room generates the SQL by comparing the exported schemas. A manual Migration is an object where you override migrate and run the SQL yourself with db.execSQL.
Mid
Auto-migration handles additions on its own: new tables, columns with a default, indices. Renames and deletions are ambiguous, so it needs an AutoMigrationSpec annotated with @RenameColumn, @DeleteColumn, @RenameTable or @DeleteTable, otherwise the build fails. Anything that moves or reshapes data, like backfilling a new column from an old one or splitting a table, needs a manual Migration. You can mix both in one database.
Senior
Auto-migration diffs the two JSON schema files at compile time; for changes SQLite's ALTER TABLE cannot express, such as a column type or nullability change, it generates a table recreation that copies the data. A spec's onPostMigrate allows small data fixes after the generated SQL. If a manual migration and an auto-migration cover the same step, Room uses the manual one. Either way the result goes through the same schema validation, and I test both kinds the same way with MigrationTestHelper.
Learn it: Room migrations
Why is fallbackToDestructiveMigration dangerous, and when is it acceptable?
Junior
When Room cannot find a migration, it drops the tables and recreates them empty, so the user's data is gone. It is fine during early development or for a database that only holds data you can download again.
Mid
It does not throw, so nothing shows up in crash reporting; users just lose data. The no-argument version is deprecated in favour of fallbackToDestructiveMigration(dropAllTables), and there are narrower variants: fallbackToDestructiveMigrationOnDowngrade for downgrades and fallbackToDestructiveMigrationFrom for specific old versions you decided not to support.
Senior
I split storage by value: user-created data lives in a database with real migrations and no fallback, while a pure cache can use destructive fallback and simply refills from the network. Where I allow it, I add a RoomDatabase.Callback with onDestructiveMigration to log the event, so a wipe is measurable. fallbackToDestructiveMigrationFrom is useful for dropping support for ancient versions deliberately instead of keeping a long chain of migrations, as long as the team has agreed that data loss for those users is acceptable.
Learn it: Room migrations
How do you test a Room migration?
Junior
With MigrationTestHelper from room-testing, usually in an instrumented test. You create the database at the old version, insert some rows, run the migration and check that the rows are still there.
Mid
createDatabase(name, oldVersion) builds the old schema from the exported JSON. I insert rows with execSQL and close it. runMigrationsAndValidate(name, newVersion, true, MIGRATION_X_Y) runs the migrations, auto-migrations included, and fails if the resulting schema does not match the new JSON. Then I query the returned database to check the data, for example that a backfilled column has the right values.
Senior
I test every shipped version to the current one, not just the latest step, because real users skip releases. For data transforms I seed edge cases (nulls, empty strings, duplicates) and assert exact values. I also run one test that opens the real database class with Room.databaseBuilder and all production migrations, to catch a migration that exists but was never registered on the builder. Schema JSON files are committed, so reviewers see the diff of every schema change.
Learn it: Room migrations
What is the difference between Preferences DataStore and Proto DataStore?
Junior
Preferences DataStore stores key-value pairs, like SharedPreferences, with typed keys such as booleanPreferencesKey. Proto DataStore stores one typed object defined by a schema, so you read and write a generated class instead of keys.
Mid
Both share the same DataStore API: a data Flow and an atomic updateData. Preferences has no schema, so nothing stops two keys with the same name and different types, and every read needs a default. Typed DataStore needs a Serializer, either for a protobuf message or for a @Serializable data class with kotlinx.serialization JSON, and gives you a whole typed object with defaults defined once.
Senior
I pick Preferences for a few independent flags and typed DataStore when settings have structure or must stay consistent with each other, since one updateData changes several fields atomically. Protobuf gives compact binary files and well-defined schema evolution (add fields with new numbers, never reuse them); JSON with kotlinx.serialization is easier to set up and fine for small objects if I keep defaults on new fields and set ignoreUnknownKeys for downgrades. In both cases I add a corruption handler and keep the store behind a repository.
Learn it: DataStore: preferences and proto
How does DataStore handle data updates?
Junior
You call updateData (or edit for Preferences) with a block that gets the current data and returns the new data. It is a suspend function, so it does not block the main thread.
Mid
updateData is an atomic read-modify-write. DataStore runs transforms one at a time, each on the latest committed value, so two concurrent toggles both apply. The data Flow emits the new value only after it is safely on disk, and if the write fails, updateData throws and the old value stays.
Senior
Internally the writes are serialized through a single queue; the new content goes to a temporary file that replaces the old one, so a crash mid-write leaves the previous file intact. That is why there must be one instance per file: two instances would each serialize their own writes and overwrite each other, so DataStore detects it and throws. Across processes the same guarantees need MultiProcessDataStoreFactory, which coordinates through file locks. The transform should be fast and pure, because it blocks the other writers while it runs.
Learn it: DataStore: preferences and proto
Why is SharedPreferences considered risky in modern Android code?
Junior
Reading values can block the main thread while the file loads, and there is no Flow to observe changes, so you need listeners.
Mid
The first get blocks until the whole XML file is parsed. apply() looks asynchronous, but pending writes are flushed synchronously when an Activity or Service stops, which shows up as ANRs on slow storage. commit() blocks outright. Neither reports a failed write in a useful way, and parse errors silently give you empty preferences.
Senior
There is also no transaction across a read and a write, so read-modify-write from two threads can lose updates, and the in-memory map can show values that never reached disk. DataStore fixes these with a suspend and Flow API, atomic updateData, write-then-swap files and exceptions for I/O errors. I migrate with SharedPreferencesMigration rather than by hand, and I do not migrate values that need encryption into a plain DataStore file.
Learn it: DataStore: preferences and proto
How would you migrate from SharedPreferences to DataStore?
Junior
Pass a SharedPreferencesMigration with the old file name in produceMigrations when you create the DataStore. It copies the old values in for you.
Mid
The migration runs before the first value is returned from data, so no screen sees defaults by mistake. After copying, it deletes the migrated keys from the old file, so it does not run again. You can pass keysToMigrate to move only some keys. For typed DataStore you use the overload that takes a function mapping the old SharedPreferencesView and the current object to the new object.
Senior
I make sure nothing else still writes the old SharedPreferences file after the release, or those writes are lost. I ship the migration with a test that seeds the old XML and checks the first emission, and I keep the migration in place for several releases, because users skip versions. If a value was stored with EncryptedSharedPreferences, it needs its own plan rather than being copied to plain DataStore.
Learn it: DataStore: preferences and proto
Why not call the Room DAO directly from the ViewModel?
Junior
The ViewModel should depend on an abstraction, not on a DAO or an API. The Repository is that abstraction. It hides where the data comes from, so the ViewModel only sees domain models.
Mid
The Repository is the one place that knows both the DAO and the network API, so the rules for combining them, like writing network results into Room and never overwriting unsynced edits, live in one class instead of every screen. If ViewModels call both, two coroutines can write the same row in any order and produce stale data.
Senior
It also makes the data layer a boundary you can enforce: entities and DAOs live in a data module and are internal, so feature modules physically cannot import them. Tests get simpler at both levels: ViewModel tests use a fake Repository, and Repository tests use a fake DAO or an in-memory Room database. It is a guideline, not a law; a tiny app with one screen may not need it, but the cost of adding it later grows with every screen.
Learn it: Repository pattern
How does the Repository handle offline-first?
Junior
It returns the cached data from Room immediately and fetches new data from the network in the background. The UI shows something instantly, even with no connection.
Mid
The Repository exposes dao.observeAll() as a Flow mapped to domain models, so the UI renders the cached result. refresh() fetches from the network and upserts into Room. Because Room's Flow query re-emits when the table is written, the UI updates when the upsert completes. If refresh fails, the cache stays and the ViewModel shows an error next to it.
Senior
Room is the single source of truth: reads only come from it, network results only go into it. Writes also go to Room first, marked as pending, and a WorkManager job syncs them, so refresh must not overwrite pending rows. With Paging 3 the same idea is a RemoteMediator that loads pages into Room while a Room PagingSource feeds the UI; network errors show up in loadState.mediator while cached pages stay on screen. I test it with a fake API that throws and assert the Flow still emits the cached list.
Learn it: Repository pattern
What should the Repository expose to the ViewModel, and when is a suspend function right?
Junior
For data that changes over time it should expose a Flow of domain models. The ViewModel collects it and the UI updates whenever the data changes.
Mid
A suspend function returns one value once. A Flow re-emits whenever the underlying data changes, which is exactly what Room's Flow queries do. If the Repository only had a suspend getAll, the ViewModel would have to call it again after every change, and other screens that changed the data would not be reflected.
Senior
For one-shot operations, like refresh(), save() or a login call, a suspend function is correct because there is no stream to observe. In the ViewModel I turn the Repository Flow into UI state with map and stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial), not by collecting it into a MutableStateFlow by hand, so collection stops when nobody is watching. Both kinds of function must be main-safe so callers never think about threads.
Learn it: Repository pattern
How would you unit-test a Repository that combines Room and Retrofit?
Junior
You give the Repository a fake DAO and a fake API, or mocks made with MockK, call its functions, and assert that the returned Flow emits the expected domain models.
Mid
You also test the mapping: give the fake API a DTO with field content and assert the emitted domain model has body. You test the offline path by having the fake DAO hold a cached entity and the fake API throw, then assert the Flow still emits the cached value and refresh throws. You use runTest from kotlinx-coroutines-test and often Turbine to read the Flow.
Senior
Fakes usually beat mocks here because they behave like the real thing, for example a fake DAO built on MutableStateFlow re-emits when its data changes, much like a Room Flow query. To check real SQL I run the DAO against Room.inMemoryDatabaseBuilder in an instrumented or Robolectric test, and for the network side I use MockWebServer to catch deserialization bugs. I also add a test for the sync rule: a pending local edit survives a refresh that returns the old server copy.
Learn it: Repository pattern
Explain how PagingSource works and what getRefreshKey does.
Junior
PagingSource loads one page at a time. load gets a key, fetches that page and returns LoadResult.Page with the items and the previous and next keys, or LoadResult.Error if it failed. A null next key means the end of the list. getRefreshKey says which key to start from when the list is reloaded.
Mid
LoadParams carries the key and loadSize, and loadSize is bigger on the first load (initialLoadSize, three pages by default). A PagingSource is a snapshot: when the data changes it is invalidated and Pager asks the factory for a new one. getRefreshKey is abstract; it receives a PagingState and should return the key for the page around anchorPosition, the last accessed index, otherwise the new source starts at the beginning and the list jumps.
Senior
For page numbers I use closestPageToPosition(anchor) and return prevKey + 1 or nextKey - 1, because a page does not store its own key. For item-keyed sources I use closestItemToPosition and its id. With offsets I can center the window on the anchor. Room's generated source handles this itself. I test sources with TestPager from paging-testing: load pages, then check the refresh key and that pages do not overlap. If a source can detect that its data is stale mid-load, it returns LoadResult.Invalid so Paging replaces it.
Learn it: Paging 3
How does RemoteMediator integrate with Paging 3?
Junior
You pass a RemoteMediator to the Pager together with a Room PagingSource. When the list needs more data than Room has, the mediator downloads it from the network and saves it to Room, and the list reads from Room.
Mid
load(loadType, state) is called with REFRESH, APPEND or PREPEND. It works out the next request from the state or from stored remote keys, fetches, writes to Room in a transaction (clearing old rows on REFRESH), and returns MediatorResult.Success with endOfPaginationReached, or MediatorResult.Error. Room invalidates its PagingSource and the UI updates from the database. Network errors show up in loadState.mediator while cached items stay on screen.
Senior
The mediator gets no key, so for cursor APIs I keep a remote-keys table written in the same transaction as the items, or use the last item when the API takes an 'after id'. initialize() decides whether to refresh on start: SKIP_INITIAL_REFRESH when the cache is younger than a TTL gives instant, offline-friendly starts. The database query order must match the server order, or appended pages land in the wrong place. I test the mediator with an in-memory Room database and a fake API, asserting rows and endOfPaginationReached for each LoadType.
Learn it: Paging 3
What does cachedIn do, and what goes wrong without it?
Junior
cachedIn(viewModelScope) keeps the loaded pages in the ViewModel, so when the screen rotates the list comes back without loading everything again.
Mid
Without it, each new collection of the Pager flow starts a fresh load, so a configuration change reloads from the start. Collecting the same PagingData twice throws, and cachedIn is what lets several collectors share one stream. Transformations like map should come before cachedIn so their results are cached too.
Senior
cachedIn multicasts the PagingData into the given scope and replays the loaded pages to new collectors. The scope must outlive configuration changes, which is why viewModelScope is right and a composable scope is not; the cache is dropped when the ViewModel is cleared. Memory is bounded by what has been loaded unless you set PagingConfig.maxSize, which drops pages far from the viewport. For a search screen I use flatMapLatest on the query to build a new Pager and apply cachedIn after it.
Learn it: Paging 3
How do you render loading, error and empty states with Paging?
Junior
LazyPagingItems has loadState with refresh, append and prepend. Each is Loading, NotLoading or Error. I show a spinner while refresh is loading, a retry button on error, and a footer spinner while appending.
Mid
I only show a full-screen error when refresh failed and itemCount is 0; with cached items I show a smaller message and keep the list. The empty state needs refresh to be NotLoading and itemCount to be 0, otherwise it flashes before the first page arrives. retry() repeats the failed load; refresh() starts over.
Senior
With a RemoteMediator, loadState.refresh combines the database and the network, so I look at loadState.mediator?.refresh to know if the network failed and loadState.source for the database. LoadState.Error carries the throwable, which I map to a user message. NotLoading's endOfPaginationReached tells me when to show an end-of-list footer. I keep all of this in the composable that owns the LazyPagingItems, so the ViewModel stays free of UI state for each load.
Learn it: Paging 3

Networking

What is the difference between an Application Interceptor and a Network Interceptor in OkHttp?
Junior
Application interceptors are added with addInterceptor and run once per call. Network interceptors are added with addNetworkInterceptor and run close to the network.
Mid
Application interceptors run once per call, even when the response comes from the cache, and see the request as your code built it. Network interceptors run for every network request, so a redirect or a retry runs them again, and they do not run for cache hits.
Senior
The chain is: application interceptors, then OkHttp's retry-and-follow-up, bridge, cache and connect interceptors, then network interceptors, then the server call. So network interceptors see headers OkHttp adds (Host, Accept-Encoding: gzip), the compressed body and chain.connection(). Application interceptors may short-circuit or call proceed more than once; network interceptors must call proceed exactly once. Auth belongs in the application layer, because OkHttp strips Authorization on a cross-host redirect and a network interceptor would add it back.
Learn it: Retrofit and OkHttp
How do you handle a 401 Unauthorized error to refresh an access token?
Junior
I use an OkHttp Authenticator. OkHttp calls it when the server returns 401, and it returns a new request with a fresh token, or null to give up.
Mid
Inside authenticate I refresh the token synchronously, save it and return response.request with the new Authorization header. The returned request does not go through application interceptors again, so the authenticator must set the header itself. If refresh fails I return null and the caller gets the 401.
Senior
Concurrent 401s each call authenticate, so I refresh inside a synchronized block and first compare the token on the failed request with the stored one; if another thread already refreshed, I retry with the stored token. I give up when response.priorResponse is already a 401, send the refresh call through a client without the authenticator, and on a 401 from the refresh endpoint clear the session and emit a logout event.
Learn it: Retrofit and OkHttp
Why should you avoid a catch-all catch (e: Exception) around a suspend network call?
Junior
Because it also catches CancellationException, which coroutines use for cancellation.
Mid
When the scope is cancelled, the suspend call throws CancellationException. A catch-all turns that into an error result, so the UI may show a false error and the code after the try keeps running. Catch HttpException, IOException and the parse exception specifically, or re-throw CancellationException first.
Senior
Catching it does not un-cancel the Job, but the function returns normally, so the caller keeps doing work: writing state, logging a fake failure, or entering a retry loop. The next cancellable suspension throws again, but non-suspending work runs until then. runCatching has the same problem. In a real codebase I check every catch-all and runCatching around suspend calls, and either re-throw CancellationException or call ensureActive() in the catch.
Learn it: Retrofit and OkHttp
What is the purpose of a connection pool in OkHttp?
Junior
It keeps connections open so they can be reused.
Mid
Reusing an open connection skips the TCP and TLS handshakes, which saves latency and battery. With HTTP/2, many requests to the same host share one connection.
Senior
By default the pool keeps up to 5 idle connections for 5 minutes. It only helps if every call goes through the same client or clients derived with newBuilder(), which share the pool and dispatcher. Separate clients each pay for their own handshakes and keep their own idle connections and threads.
Learn it: Retrofit and OkHttp
Why would a team choose Ktor over Retrofit for a Kotlin Multiplatform project?
Junior
Ktor client is written in Kotlin and runs on Android, iOS, desktop and web. Retrofit only runs on the JVM. With Ktor the networking code can live in commonMain and be shared.
Mid
The client setup and calls (ContentNegotiation, HttpTimeout, Auth) are written once in common code, and each platform adds an engine: OkHttp or Android on Android, Darwin on iOS. Retrofit is JVM-only because it relies on Java dynamic proxies and reflection, so iOS would need a second stack.
Senior
The trade-off is ergonomics: Retrofit gives a declarative interface, while Ktor is imperative and you write URLs and parameters in code. Neither validates URLs at compile time (Retrofit validates annotations when a method is first used). Ktor also gives KMP tests MockEngine. For an Android-only app with an existing OkHttp and Retrofit stack, there is little reason to switch; for KMP, Ktor plus kotlinx.serialization is the standard choice.
Learn it: Ktor client
How does ContentNegotiation work, and what happens if you forget to install it?
Junior
ContentNegotiation converts request and response bodies to and from Kotlin objects using kotlinx.serialization. Without it, body<User>() fails because Ktor does not know how to convert the bytes into a User.
Mid
json() registers a kotlinx.serialization converter for application/json. On a response, body<User>() finds the converter for the response Content-Type and decodes with your Json instance. It also adds an Accept header. Without the plugin, body<User>() throws NoTransformationFoundException. You can still read bodyAsText() or body<String>().
Senior
You can register several converters (JSON, XML, CBOR, protobuf) for different content types. Typical problems: a server sending the wrong Content-Type so no converter matches, a class missing @Serializable so the serializer lookup fails at runtime, and no ignoreUnknownKeys so a new field breaks parsing. With expectSuccess off, an error body also reaches the converter, so parse errors can really be HTTP errors.
Learn it: Ktor client
How does Ktor's Auth plugin handle a 401, and how does that compare to an OkHttp Authenticator?
Junior
With bearer auth you give loadTokens to read saved tokens and refreshTokens to get new ones. When a request gets 401, Ktor calls refreshTokens and retries the request with the new token.
Mid
loadTokens is called once and the result is cached. On 401, refreshTokens runs with oldTokens and the client; if it returns new BearerTokens, they replace the cache and the request is retried. If it returns null, the 401 response is returned. The refresh request is marked with markAsRefreshTokenRequest() so its own 401 does not trigger another refresh.
Senior
Ktor single-flights the refresh: if several requests get 401 for the same token, refreshTokens runs once and the others reuse the result. With OkHttp you write that yourself with a synchronized block and a check whether the token already changed. In both I make sure a failed refresh clears the session, sendWithoutRequest is limited to our host, and the refresh endpoint cannot loop.
Learn it: Ktor client
What are the three timeouts in HttpTimeout and why are they separate?
Junior
connectTimeoutMillis, socketTimeoutMillis and requestTimeoutMillis. They control different phases of a network call.
Mid
connectTimeoutMillis limits establishing the connection. socketTimeoutMillis is the longest allowed gap between two data packets. requestTimeoutMillis limits the whole call. They are separate because a server that sends a little data every 5 seconds never trips a 10-second socket timeout, but a 30-second request timeout still stops the call.
Senior
Ktor passes connect and socket timeouts to the engine (with OkHttp: connectTimeout, readTimeout and writeTimeout) and enforces the request timeout itself. Without the plugin there are no Ktor limits, only engine defaults. Timeouts can be overridden per request with timeout { }, for example a longer request timeout for uploads. Timeout errors (HttpRequestTimeoutException, ConnectTimeoutException, SocketTimeoutException) should map to a network error, and HttpRequestRetry only retries them with retryOnException(retryOnTimeout = true).
Learn it: Ktor client
What happens when the server adds a new field to a JSON response?
Junior
With kotlinx.serialization the default is to throw a SerializationException because the key is unknown. You fix it by setting ignoreUnknownKeys = true on the Json instance. Moshi and Gson ignore unknown keys by default.
Mid
The generated deserializer reads each key and looks it up in the class descriptor. If the key is unknown and ignoreUnknownKeys is false, decoding throws. The usual incident is a backend deploy adding a field and every installed app version failing on that response. I enable the flag on the shared Json and keep a unit test that decodes a body with extra keys.
Senior
I check that every Json instance used for responses has the flag, ideally by having only one, provided from DI. The trade-off is that ignoreUnknownKeys also hides renamed fields: if user_name becomes username, the old key disappears and the new one is ignored. Required fields still fail loudly, and contract tests against recorded responses catch fields that silently fall back to a default.
Learn it: Serialization: kotlinx vs Moshi
Why do teams migrate from Gson to kotlinx.serialization or Moshi?
Junior
Gson can fill a missing Int with 0, a missing Boolean with false, and even put null into a non-null String. kotlinx.serialization and Moshi throw for a missing required field and use the Kotlin default for an optional one.
Mid
Gson uses Java reflection and knows nothing about Kotlin nullability or default values. When a class has no no-arg constructor, Gson creates it without running the constructor, so defaults are skipped and missing fields get JVM zero values. kotlinx.serialization uses a serializer generated by the compiler plugin, Moshi codegen generates adapters with KSP, and both respect Kotlin types.
Senior
The migration risk is that code which relied on Gson's silent values now throws, so I audit each model against the real API: truly optional fields get a correct default or a nullable type, required ones stay required. I also check custom TypeAdapters, @SerializedName mappings and R8 rules. kotlinx.serialization is the choice if models may move to KMP or Ktor; Moshi is fine for an Android-only Retrofit stack.
Learn it: Serialization: kotlinx vs Moshi
How do you wire kotlinx.serialization into Retrofit?
Junior
Add com.squareup.retrofit2:converter-kotlinx-serialization, create a Json instance, and call addConverterFactory(json.asConverterFactory("application/json".toMediaType())). The service functions can then return @Serializable types.
Mid
Retrofit asks each converter factory in the order they were added whether it can handle the declared type, and the first one that accepts wins. The media type you pass is the Content-Type for request bodies the converter writes. Common mistakes are creating a new Json per Retrofit instance or forgetting ignoreUnknownKeys.
Senior
Factory order matters: JSON converters like the kotlinx and Moshi ones accept almost any type, so a more specific factory such as ScalarsConverterFactory for plain String responses must be added before them. I provide the Json and Retrofit instances from one DI module and test the configured Retrofit against MockWebServer with real response fixtures, including unknown keys and missing optional fields.
Learn it: Serialization: kotlinx vs Moshi
What is the null-safety problem with Gson and how does kotlinx.serialization solve it?
Junior
Gson can put null into a Kotlin String declared as non-null, and fill missing numbers and booleans with 0 and false. kotlinx.serialization throws MissingFieldException for a required field and uses the Kotlin default for an optional one.
Mid
Gson only sees Java fields. Without a no-arg constructor it allocates the object without running the constructor, so Kotlin's null checks and default values never run. The null shows up later as a NullPointerException in UI code. kotlinx.serialization's generated serializer checks presence and nullability while decoding, so the error appears at the parsing boundary.
Senior
kotlinx.serialization is strict in both directions: a missing required key throws MissingFieldException, and an explicit JSON null for a non-null property throws too, unless coerceInputValues is on and the property has a default. explicitNulls = false lets a missing nullable key decode as null. I pick a nullable type when absent must be visible, a default only when it is a correct value, and test decoding with each optional field removed.
Learn it: Serialization: kotlinx vs Moshi
What happens if you catch CancellationException and return a default value instead of re-throwing it?
Junior
The coroutine was asked to stop, but your code acts as if a normal error happened and keeps going. It might show an error message or update state for a screen that is already closed.
Mid
Catching it does not un-cancel the Job. The function returns normally, so the caller keeps running until it reaches the next cancellable suspension point, where it throws again. Meanwhile it can write to state, log a fake failure or start a retry. catch (e: Exception) and runCatching both catch it, so I re-throw it first or catch only specific exceptions.
Senior
Non-suspending work after the catch still runs, so a loop that catches and does not suspend can keep spinning after cancellation. I treat every catch-all around suspend code as a review flag: re-throw CancellationException or call ensureActive() in the catch. withTimeout's TimeoutCancellationException is also a CancellationException, so I use withTimeoutOrNull when a timeout should be a value. Cleanup that must suspend during cancellation goes in withContext(NonCancellable).
Learn it: Error handling and result types
How do you map Retrofit and OkHttp exceptions to a UI-friendly result type?
Junior
Wrap the call in try-catch and return a sealed type with success and error variants, so the UI can show a message.
Mid
IOException means the request did not complete, HttpException or a non-2xx Response means the server answered with an error, and SerializationException means the body did not match the model. Each maps to its own sealed subtype, CancellationException is re-thrown, and the UI shows a different message for each.
Senior
Per endpoint I choose Response<T> when I need the status or error body, and a bare T when HttpException is enough. Exception types depend on the converter: kotlinx.serialization throws SerializationException, Moshi throws JsonDataException, and its JsonEncodingException is an IOException that a plain IOException catch would call a network error. Tests use MockWebServer for each path: timeout, 404, 500, malformed JSON, 204.
Learn it: Error handling and result types
When should you retry a network call, and how do you avoid duplicate side effects?
Junior
Retry when the request failed for a temporary reason, like no network or a 503, with a delay between attempts.
Mid
Retry only idempotent methods such as GET, PUT and DELETE, only for transient failures (IOException, 503, maybe 429 with Retry-After), with exponential backoff and a small attempt limit. 4xx errors and parse errors are not retried because they will fail again.
Senior
A timeout on a POST does not tell you whether the server did the work, so POSTs are retried only with a client-generated idempotency key reused across attempts. I add jitter so many clients do not retry in sync after an outage. The policy lives in one place (a helper or OkHttp interceptor) and the delay is cancellable, so leaving the screen stops the retries.
Learn it: Error handling and result types
Sealed class, sealed interface, and Result<T> from the standard library: when do you use each?
Junior
Result<T> holds either a value or a Throwable. A sealed class or sealed interface lets you name each outcome, like Network, Http and Parse, and the compiler checks that a when handles all of them.
Mid
Since Kotlin 1.5, direct subtypes of both a sealed class and a sealed interface must be in the same module and package, not the same file. A sealed interface lets one type implement several sealed hierarchies and works well with data objects; a sealed class can hold shared state in a constructor. Result has no public subtypes to match on; you use fold, getOrElse or onFailure, and the error is just a Throwable.
Senior
runCatching catches every Throwable including CancellationException, so I avoid it around suspend calls unless cancellation is re-thrown. I use a sealed result per layer, a network result in the data layer mapped to domain errors the UI understands, so screens do not depend on Retrofit types. Result<T> is fine inside a layer for simple success-or-throwable cases.
Learn it: Error handling and result types
Where do you add the Authorization header in OkHttp, and why not in a network interceptor?
Junior
In an application interceptor added with addInterceptor. It builds a new request with the header and calls chain.proceed.
Mid
An application interceptor runs once per call with the request my code built. A network interceptor runs for every network request, including redirects. OkHttp removes Authorization when it follows a redirect to another host, and a network interceptor would add it back, sending the token to that host.
Senior
The chain order is application interceptors, then retry-and-follow-up (where the Authenticator runs), bridge, cache, connect, network interceptors and the server call. So a request returned by the Authenticator skips application interceptors and must carry the new header itself. I keep the token in a @Volatile field or StateFlow so OkHttp threads see a refresh at once, and only attach it for our API host.
Learn it: Auth tokens and interceptors
What happens when 20 concurrent calls all get a 401?
Junior
OkHttp calls the Authenticator once for each 401. Without special handling, 20 refresh requests are sent.
Mid
I put the refresh in a synchronized block. The first thread refreshes; the others wait on the lock. Inside the lock each one compares the token on its failed request with the stored token, and if it already changed it retries with the stored token instead of refreshing again.
Senior
The lock alone just runs 20 refreshes one after another; the re-check makes it a single flight. I also return null when priorResponse is already a 401, send the refresh through a client without the authenticator, and treat Rejected and Failed refreshes differently. In suspend code the same pattern uses Mutex.withLock. I test it with MockWebServer, firing concurrent calls and asserting one refresh request.
Learn it: Auth tokens and interceptors
How do you handle the case where the refresh token itself is expired?
Junior
If the refresh endpoint rejects the refresh token, clear both tokens and send the user to the login screen.
Mid
I separate a rejected refresh (400 or 401 from the token endpoint) from a failed one (no network, timeout, 5xx). Rejected clears the session and emits a logout event; failed makes the Authenticator return null, so this call fails with 401 and the user can retry, but stays logged in.
Senior
I model it as a sealed RefreshResult (Success, Rejected, Failed). The authenticator cannot navigate, so clear() emits an event on an app-level flow that the UI layer collects to show login. I may also refresh proactively when the stored expiry is near, but keep the 401 path because clocks drift and servers revoke tokens. Tests cover each result with a fake refresher.
Learn it: Auth tokens and interceptors
Where should the refresh token be stored, and why?
Junior
Encrypted, with the key in the Android Keystore, not in plain SharedPreferences.
Mid
Plain SharedPreferences are a readable XML file for anyone with root, a debuggable build, or a backup copy. Encrypting with a Keystore key means the file alone is useless. EncryptedSharedPreferences did this, but Jetpack Security Crypto is deprecated, so new code often uses Tink with DataStore.
Senior
Keystore keys do not leave the device, so a backup restored elsewhere cannot decrypt the tokens; I exclude the token file with dataExtractionRules (or allowBackup=false) so a restore starts logged out cleanly. Room versus SharedPreferences does not matter; encryption does. In KMP I use expect/actual secure storage: Keystore-backed encryption on Android, Keychain on iOS.
Learn it: Auth tokens and interceptors
What is the difference between OkHttp's HTTP cache and using Room as a single source of truth?
Junior
The HTTP cache stores whole responses on disk and reuses them based on the server's headers. With Room as the single source of truth, the app saves data in the database and the UI always reads from there, so it works offline.
Mid
The HTTP cache is transparent and per URL: freshness comes from Cache-Control and revalidation from ETag or Last-Modified, and it only helps when you make the request again. Room gives queryable rows, a Flow that updates the UI after every write, and freshness rules the app controls, like a TTL per data type. The cost is entities, DAOs, mapping and refresh logic.
Senior
I use both: Room as the source of truth for anything the user sees or edits offline, and the HTTP cache underneath so refreshes revalidate cheaply with a 304. The HTTP cache depends entirely on correct server headers, so I agree them per endpoint with the backend rather than rewriting them in interceptors. Writes go to Room first and sync later, so a refresh must not overwrite unsynced local changes.
Learn it: Caching and offline reads
How would you show data offline and keep it reasonably fresh?
Junior
Read from the local database so something shows immediately, and fetch from the network in the background to update it. If the network fails, the saved data stays on screen.
Mid
The repository exposes a Flow from Room. Each row stores fetchedAt. On screen open the ViewModel calls refreshIfStale, which only fetches when the row is missing or older than a TTL; pull-to-refresh forces it. The fetch upserts into Room, and the Flow re-emits. Errors become UI state next to the cached data.
Senior
That is stale-while-revalidate at the app level. The details that matter: TTL per data type; distinct states for loading with no data, offline with no data and stale data; cancelling outdated refreshes with collectLatest so a slow old response cannot overwrite a newer one; and periodic sync with WorkManager for data that must be fresh when the app opens. I test it with a fake clock and a fake API that fails.
Learn it: Caching and offline reads
What are ETags and how do they work?
Junior
An ETag is a version identifier the server sends with a response. If the data has not changed, the server can reply that the client's copy is still good instead of sending it again.
Mid
The server sends ETag in the response. Next time, the client sends it back in If-None-Match. If the resource is unchanged, the server returns 304 Not Modified with no body, and the client uses its stored copy; otherwise it returns 200 with the new body and a new ETag.
Senior
With a Cache configured, OkHttp does this itself: once max-age has expired, or with no-cache, it sends the conditional request and turns a 304 into a normal response built from the stored body, so Retrofit code does not change. A 304 still costs a round trip, so for data that changes rarely a sensible max-age avoids the request entirely. Without an HTTP cache, you can store the ETag yourself next to the Room rows and send it manually.
Learn it: Caching and offline reads
What are the risks of a local database cache?
Junior
It can show out-of-date data, and it uses storage on the device.
Mid
Stale data, if nothing triggers a refresh. Growth without limit, if old rows are never deleted. And migrations: every schema change needs one, or users crash on upgrade.
Senior
Consistency is the hard part: a refresh can overwrite unsynced local edits, out-of-order responses can replace newer data, and rows deleted on the server stay forever unless the refresh removes them, for example by replacing a query's result set in one transaction. I keep data that can be re-downloaded in a separate cache database where destructive migration is acceptable, and user data in one with real migrations. I also decide what to show when the cache is very old, for example a 'last updated' label.
Learn it: Caching and offline reads

Dependency injection

What is the difference between dependency injection and a service locator?
Junior
DI passes dependencies into a class from the outside, usually through the constructor. A service locator is a global registry the class calls to fetch its own dependencies at runtime. DI is preferred because the class does not need to know about the registry.
Mid
With DI the class depends on an interface and the caller decides the implementation. With a service locator the class still references the concrete type and the registry object, so coupling is hidden but not removed. In Hilt, @Inject constructor is DI; calling EntryPointAccessors.fromApplication(...) deep inside a class to fetch a dependency is service-locator style and should be kept to places Hilt cannot reach.
Senior
The deeper difference is where the decision lives. DI pushes the decision to the composition root, making the dependency graph explicit and inspectable. A service locator also centralises the decision, but each class pulls from global state, so tests must configure and reset that registry, and a missing entry fails at runtime on the line that asks for it. In a codebase review I look for global get() or getInstance() calls inside domain and presentation classes. Koin's container works like a locator internally, but if only module definitions call get() and classes take constructor parameters, the classes themselves are still DI-friendly.
Learn it: Why dependency injection
Why constructor injection over field or property injection?
Junior
Constructor injection makes the dependency visible in the type signature and the object is fully initialised after construction. Field injection leaves the object in a half-built state until the framework sets the field.
Mid
With constructor injection you can mark the property val, and the object cannot exist without its dependencies. Field injection needs lateinit var, and code that touches the field before injection throws UninitializedPropertyAccessException. In Hilt, field injection is used only in Activities, Fragments, Services and other classes the system instantiates.
Senior
Dagger validates both styles at build time, so the difference is not safety but design: a constructor lists every dependency, which makes a class with too many of them obvious, and it lets the class be built in a plain test without any framework. In Activities Hilt injects fields in super.onCreate(), so using them before that point crashes. With Koin, missing definitions only show up at runtime, which is why teams add a verify() test.
Learn it: Why dependency injection
How does DI make unit testing easier? Give a concrete example.
Junior
You pass a fake or mock object into the constructor instead of the real one. The test runs without a device, network, or database.
Mid
For example, a UserViewModel takes a UserRepository interface. In production the container passes NetworkUserRepository; in a test you pass FakeUserRepository with a Map. The test is a plain Kotlin function, no Robolectric, no @RunWith. The pitfall is if the ViewModel creates the repository internally, you cannot swap it without reflection.
Senior
The interface is the boundary. If it is too wide, the fake is hard to write and teams fall back to mocks, so keep interfaces focused on what callers need. Most tests just call the constructor; framework-level replacement is for integration tests: in Hilt, @TestInstallIn replaces a module for the whole test source set and @UninstallModules plus a nested @InstallIn module replaces it for one test class; in Koin you load a test module or override definitions. I also keep fakes honest by running the same contract tests against the fake and the real implementation.
Learn it: Why dependency injection
When would you choose Koin over Hilt, or vice versa?
Junior
Hilt is the default for pure Android apps because it integrates with the Android lifecycle. Koin is a runtime DSL that works without code generation.
Mid
Hilt fails at compile time if a binding is missing; Koin fails at runtime when the object is first requested. Koin is a better fit for Kotlin Multiplatform because Hilt is Android-only. The trade-off is that Koin requires you to call verify() or write a smoke test to catch missing bindings early.
Senior
In a large Android-only team, Hilt's build-time graph validation, Jetpack integrations (ViewModels, WorkManager, Navigation) and Android Studio's navigation between injection sites pay off. In a KMP project Koin modules can live in shared code used by Android and iOS, and without annotation processing the build stays simpler; Koin Annotations or the Koin compiler plugin can add compile-time checks if needed. The real question in an interview is whether you can explain the trade-off without saying one is universally better. A senior answer also mentions that the DI concept is identical; only the wiring syntax and failure timing differ.
Learn it: Why dependency injection
What is the difference between @Provides and @Binds?
Junior
@Provides is a function whose body creates and returns an instance, for example building Retrofit. @Binds is an abstract function that tells Hilt which implementation to use for an interface. @Provides goes in an object module; @Binds goes in an abstract class or interface module.
Mid
@Binds works when Hilt can already build the implementation, usually through an @Inject constructor, and you just need to expose it as the interface. @Provides is for anything that needs code: builders, third-party classes, values from config. A @Provides that just returns its parameter is a sign it should be @Binds.
Senior
@Binds has no body, so Dagger can treat it as an alias and generates less code than for an equivalent @Provides method. Both are type-checked and validated at build time. Scopes and qualifiers work on both: a scope on a @Binds method scopes the binding, and a qualifier goes on the method. Because Kotlin object modules are static, @Provides there needs no module instance. If I need both kinds in one module I put the @Provides in a companion object of the abstract module.
Learn it: Hilt basics
What happens when you inject an unscoped dependency?
Junior
Hilt creates a new instance every time the dependency is injected. Nothing is cached.
Mid
Each injection gets its own instance, even inside the same Activity. If two ViewModels inject an unscoped repository, they get two separate objects. Installing the module in SingletonComponent does not change that; only a scope annotation such as @Singleton does.
Senior
Unscoped is the right default for cheap, stateless objects, because scoped bindings cost a little: Dagger wraps them in a double-checked lock and keeps them alive as long as the component. Expensive or shared objects (OkHttpClient, Retrofit, a Room database, an in-memory cache) need a scope. To check a binding I log in the constructor or provide method and count calls during a flow, or inject it twice in a @HiltAndroidTest and compare references.
Learn it: Hilt basics
How does Hilt integrate with Activities, Fragments and ViewModels?
Junior
You put @HiltAndroidApp on the Application class and @AndroidEntryPoint on Activities and Fragments. ViewModels use @HiltViewModel with an @Inject constructor and are obtained with hiltViewModel() in Compose or by viewModels() in a Fragment.
Mid
@AndroidEntryPoint generates a base class that creates the right component and injects @Inject fields: in super.onCreate() for an Activity and in onAttach() for a Fragment. A @HiltViewModel is built in ViewModelComponent, so it can get SavedStateHandle and @ViewModelScoped bindings, and it survives configuration changes like any ViewModel.
Senior
For values only the screen knows, like an item id, I use assisted injection: @HiltViewModel(assistedFactory = DetailViewModel.Factory::class), an @AssistedInject constructor with an @Assisted id, and an @AssistedFactory interface; in Compose hiltViewModel<DetailViewModel, DetailViewModel.Factory> { it.create(id) }. For classes Hilt cannot annotate, such as a ContentProvider, I declare an @EntryPoint interface and use EntryPointAccessors. I keep EntryPoints at those edges, since using them inside ordinary classes turns Hilt into a service locator.
Learn it: Hilt basics
How would you test code that uses Hilt?
Junior
For a ViewModel unit test I do not need Hilt: I call the constructor with a fake repository. For tests of the real wiring, I annotate the test with @HiltAndroidTest and replace modules with test modules.
Mid
A Hilt test has @HiltAndroidTest, a HiltAndroidRule whose inject() is called before use, and runs on HiltTestApplication, through a custom instrumentation runner or Robolectric's @Config. @TestInstallIn(components = [SingletonComponent::class], replaces = [NetworkModule::class]) swaps a module for every test in that source set.
Senior
I keep most tests as plain JVM tests with constructor injection, because Hilt tests build a component per test and are slower. For one test class that needs different bindings I use @UninstallModules with a nested @InstallIn module, or @BindValue on a field, instead of a global @TestInstallIn. Hilt tests then cover the wiring that unit tests cannot: that the graph builds, that scopes give the expected sharing, and that WorkManager and ViewModel integrations resolve.
Learn it: Hilt basics
Explain the Hilt component hierarchy and what each scope means.
Junior
SingletonComponent lives for the whole app, ActivityComponent for one Activity and FragmentComponent for one Fragment. Each has a scope annotation: @Singleton, @ActivityScoped, @FragmentScoped. A child component can use bindings from its parent.
Mid
SingletonComponent is the root. Under it are ActivityRetainedComponent, which survives configuration changes, and ServiceComponent. ViewModelComponent and ActivityComponent are both children of ActivityRetainedComponent; FragmentComponent and ViewComponent are under ActivityComponent. A child sees its ancestors' bindings, never the reverse, and a scope annotation must match the component the binding lives in.
Senior
The tree encodes lifetimes so the compiler can stop leaks: ViewModelComponent sits under ActivityRetainedComponent, not ActivityComponent, so a ViewModel cannot inject an Activity or an @ActivityScoped object that would leak across rotation. SingletonComponent is the root Dagger component and the others are generated as subcomponents. Each component also gets default bindings, like the Activity in ActivityComponent and SavedStateHandle in ViewModelComponent. For cleanup, @ActivityRetainedScoped objects can use ActivityRetainedLifecycle.addOnClearedListener, since Hilt does not close scoped objects itself.
Learn it: Hilt scopes and components
What does scoping cost, and when is it worth it?
Junior
A scoped object stays in memory for as long as its component lives. A @Singleton stays for the whole process, so you should not make everything a singleton.
Mid
Besides memory, a scoped object's state is shared by everyone who injects it, so per-user or per-screen data in a singleton leaks between screens and sessions. Unscoped objects are cheap to create and have no shared state, so they are the default. I scope when an object is expensive (OkHttpClient, a database) or when sharing is the point (a cache).
Senior
Dagger wraps a scoped provider so the first instance is cached; for @Singleton that is a double-checked lock on first access, which is small but not zero, and the object can never be collected while the component lives. The bigger cost is design: scoped state makes test isolation and logout harder. I pick the narrowest component that matches the object's real lifetime, for example @ViewModelScoped to share state between one ViewModel's dependencies, and I check the result by injecting twice in a @HiltAndroidTest and comparing references.
Learn it: Hilt scopes and components
A developer put @Singleton on a class that holds a reference to a ViewModel or Activity. What goes wrong and how do you fix it?
Junior
The singleton lives for the whole app, so the ViewModel or Activity it holds can never be garbage-collected. That is a memory leak. The fix is to remove the reference or change the scope.
Mid
Beyond the leak, the singleton keeps talking to a dead object: a cleared ViewModel or a destroyed Activity, so updates go nowhere. The fix is to pass plain data instead of the lifecycle object, or move the class to the component that matches the referenced object, such as @ActivityScoped with the Activity injected by Hilt.
Senior
The root cause is a lifetime mismatch: the holder's scope is wider than the object it references. Hilt prevents some of this at build time, since a SingletonComponent binding cannot inject the Activity or @ActivityContext, but it cannot stop code that registers this into a singleton at runtime. I look for singletons with register or listener methods that take an Activity, Fragment, View or ViewModel, and run LeakCanary in debug builds plus its instrumentation rule in UI tests so a leak fails CI.
Learn it: Hilt scopes and components
How do you test a class whose dependencies come from Hilt?
Junior
For a unit test I create the class with fakes passed to the constructor. Hilt is not needed for that.
Mid
For tests of the real graph I use @HiltAndroidTest with a HiltAndroidRule on HiltTestApplication. A test module with @TestInstallIn(components = [SingletonComponent::class], replaces = [NetworkModule::class]) provides a fake API for every test in the source set.
Senior
I keep most tests as plain constructor tests because they are fast and need no Android runtime. Hilt tests check what only the graph can show: that it builds, that scoped bindings are shared as intended, and that integrations resolve. For one test class I use @UninstallModules with a nested @InstallIn module, or @BindValue for a single fake, so the global replacement stays rare. Because every Hilt test gets a fresh component, singletons do not leak state between tests, but a Kotlin object or a static field still would.
Learn it: Hilt scopes and components
What is the difference between Hilt and Koin?
Junior
Hilt generates the dependency graph at build time with annotations. Koin builds it at runtime from a Kotlin DSL. A missing dependency is a build error in Hilt and a runtime crash in Koin.
Mid
Hilt is built on Dagger and integrates with Android through @AndroidEntryPoint, @HiltViewModel and fixed components and scopes. Koin uses module, single, factory and viewModel definitions loaded by startKoin, with no code generation, so setup is simple and it works in Kotlin Multiplatform. The cost is that Koin's graph is only checked when it runs, so you add a verify() test.
Senior
I compare them on failure timing, platform reach and team scale. Hilt finds graph errors at build time and gives a standard structure that suits large Android-only teams, at the cost of annotation processing time and Dagger's error messages. Koin keeps the build simple and runs in shared KMP code, at the cost of runtime resolution; verify() tests, or Koin Annotations and the compiler plugin, close most of the gap. Either way the classes look the same: constructor injection, with the framework only doing the wiring.
Learn it: Koin as an alternative
Is Koin a dependency injection framework or a service locator?
Junior
Koin calls itself a DI framework, but its container works like a service locator: it looks up types in a registry at runtime.
Mid
It depends on how you use it. If classes take their dependencies in the constructor and only module definitions call get(), the classes are using DI and Koin is the wiring. If classes call get() or by inject() themselves, that is the service locator pattern.
Senior
The container is a runtime registry, so it cannot prove the graph is complete before it runs; that is the real consequence of the locator-style mechanism, and verify() or compile-time tooling addresses it. In code review I look at where get() and inject() are called: in modules and Android entry points such as an Activity they are fine; inside repositories, use cases or ViewModels they hide dependencies and force tests to start Koin.
Learn it: Koin as an alternative
How do you handle object lifetimes in Koin?
Junior
single gives one shared instance and factory gives a new instance each time. viewModel is for Android ViewModels.
Mid
single lives as long as the Koin container, factory is created per resolution, and viewModel instances are stored in the ViewModelStoreOwner so they survive rotation and are cleared with it. Runtime values like an item id are passed with parametersOf.
Senior
For lifetimes between app-wide and per-call, Koin has scopes: scope<MyActivity> { scoped { ... } } with an activity scope, or a custom scope I create and close myself, for example for a logged-in session that is closed on logout. Closing the scope drops its instances, which is cleaner than a single that must be cleared by hand. Like Hilt, the narrowest lifetime that matches the object's state is the right one.
Learn it: Koin as an alternative
How do you make sure a Koin configuration is complete?
Junior
By writing a unit test that checks the modules, instead of waiting for the app to crash.
Mid
In Koin 4 I call module.verify() from koin-test in a JVM unit test. It checks that every constructor parameter of every definition has a definition. Types Koin provides at runtime, like Context or SavedStateHandle, go in extraTypes. checkModules() is deprecated since Koin 4.0.
Senior
verify() checks constructor types statically, so it catches missing definitions but not definitions that throw when built, or wrong runtime parameters. For those I keep a few instrumented smoke tests that open each screen. If the team wants build-time guarantees, Koin Annotations with KSP or the Koin compiler plugin check the graph during compilation. I run the verify test in CI on every PR so a missing definition never reaches a release.
Learn it: Koin as an alternative

Background work

When would you choose WorkManager over a coroutine, a foreground service or an alarm?
Junior
WorkManager is for background work that must finish even if the user leaves the app, like syncing or uploading logs. A coroutine in viewModelScope is for work that only matters while the screen is open. A foreground service is for long work the user can see, like music playback. An alarm is for something at an exact time.
Mid
WorkManager persists requests, survives process death and reboot, supports constraints and retries, but it is deferrable and each run gets about ten minutes. A foreground service runs now and keeps running, but needs a visible notification, a foregroundServiceType, and on Android 14 the matching permission, and since Android 12 it generally cannot be started from the background. Exact alarms need the exact-alarm permission on Android 12+ and are cleared on reboot.
Senior
I decide by the guarantee the user needs. 'Must finish eventually' is WorkManager. 'Must start now and the user is waiting' is expedited work if it is short, or a foreground service if it is long. 'Must happen at 7:00' is an alarm that may then enqueue work. WorkManager 2.12 requires minSdk 24, and persisted work is scheduled through JobScheduler, so the system batches it with other apps' jobs and applies Doze and standby buckets. Work can therefore run late, and the UI should say 'syncing when connected' rather than promise a time.
Learn it: WorkManager
Explain the unique-work policies and when you would use each.
Junior
Unique work has a name, and the policy decides what happens if work with that name already exists. KEEP ignores the new request, REPLACE cancels the old one and enqueues the new one, and APPEND runs the new one after the old one.
Mid
One-time work uses ExistingWorkPolicy: KEEP, REPLACE, APPEND and APPEND_OR_REPLACE, which starts a new chain if the existing one failed instead of failing with it. Periodic work uses ExistingPeriodicWorkPolicy: KEEP, UPDATE and CANCEL_AND_REENQUEUE. For a periodic sync scheduled at startup I use KEEP; when a release changes its interval or constraints I use UPDATE, which applies the change without cancelling a running worker.
Senior
The common bug is REPLACE or CANCEL_AND_REENQUEUE in code that runs on every launch: it cancels in-flight work and resets its attempt count. I check every enqueueUnique call for the intent: deduplicate (KEEP), latest wins (REPLACE, for example a search index rebuild with new parameters), or ordered queue (APPEND_OR_REPLACE for uploads that must go in order without one failure blocking the rest). I also make the work itself idempotent, since a worker can be stopped midway and run again.
Learn it: WorkManager
How does backoff work in WorkManager?
Junior
When a worker returns Result.retry(), WorkManager waits and runs it again. With EXPONENTIAL the wait doubles each time; with LINEAR it grows by the same amount each time.
Mid
setBackoffCriteria sets the policy and initial delay. The default is exponential with 30 seconds, the minimum is 10 seconds, and delays are capped at 5 hours, so exponential gives 30 s, 60 s, 120 s. There is no built-in retry limit; the worker checks runAttemptCount and returns failure after a few attempts. Result.failure() stops the work and fails anything chained after it.
Senior
The delay is the earliest time of the next attempt, not an exact time: constraints, Doze and standby buckets can push it later. I separate errors in doWork: IOException and 5xx retry, 4xx and parsing errors fail, and CancellationException is rethrown because it means the system stopped the worker. To check behaviour I use TestListenableWorkerBuilder with a given runAttemptCount to assert the Result, and the Background Task Inspector to watch real retries.
Learn it: WorkManager
What are the Data size limit and expedited work, and what traps do they hide?
Junior
Input and output Data are limited to 10 KB each. For more, you save the data in a file or database and pass its id. Expedited work asks WorkManager to run something important as soon as possible.
Mid
Building a Data object over 10,240 bytes throws, so passing a JSON payload works in tests with small data and crashes in production with large data. Expedited work is set with setExpedited and an OutOfQuotaPolicy, which says what to do when the app's quota runs out: run as normal work or drop the request. Only one-time work can be expedited.
Senior
On Android 12+ expedited work becomes an expedited job with no notification; on Android 11 and lower WorkManager runs it as a foreground service, so the worker must override getForegroundInfo() to provide a notification, otherwise it fails only on older devices. With WorkManager's minimum SDK at 24, that means Android 7 to 11 still take that path. For chains, parallel parents' outputs are merged into the child's input with an InputMerger, and the merged output also has to fit in 10 KB.
Learn it: WorkManager
What happens if a service started with startForegroundService() does not call startForeground() in time?
Junior
The service has about 5 seconds to call startForeground with a notification. If it does not, the system shows an ANR and the app crashes.
Mid
The window starts when startForegroundService() is called. Since Android 12 the crash is a ForegroundServiceDidNotStartInTimeException. The fix is to call startForeground (I use ServiceCompat.startForeground) at the top of onStartCommand with a simple notification, before any async work, and update the notification later.
Senior
I treat promotion as the first statement of onStartCommand, and I keep the service's own start fast: no disk or network reads before it, and onCreate kept light, because a slow main thread at process start eats into the 5 seconds. I check the main-thread work during cold start with a trace when these crashes show up only on low-end devices. For starts that might not need foreground work at all, I decide before calling startForegroundService, not inside the service.
Learn it: Foreground services
What changed for foreground services in Android 14 and 15?
Junior
Android 14 requires a foregroundServiceType for each foreground service and a matching permission, for example FOREGROUND_SERVICE_MEDIA_PLAYBACK for audio.
Mid
On target 34 the service must declare its type in the manifest, the app must hold FOREGROUND_SERVICE plus the type permission, and some types need a runtime permission too, like location for the location type. Missing pieces throw MissingForegroundServiceTypeException or SecurityException. There is also a shortService type that needs no permission but must finish in about 3 minutes. Android 15 limits dataSync and mediaProcessing to 6 hours in 24 hours and calls onTimeout when the time is up.
Senior
Google Play also asks you to declare and justify each type you use, so the type is a product decision, not just a constant. I pick the narrowest type that fits, use shortService for short critical work, and move bulk transfers to WorkManager or the user-initiated data transfer job where it fits, because dataSync is the type most affected by the new limits. I implement onTimeout to save progress and stop, and keep dataSync work resumable so a stop costs little.
Learn it: Foreground services
When would you choose a foreground service over WorkManager?
Junior
Use a foreground service when the user started something they can see and it must keep running, like music or navigation. Use WorkManager for background tasks like uploads and sync.
Mid
A foreground service runs now, keeps the process at high priority and has a notification, but it needs a type, permissions, and since Android 12 it usually cannot be started from the background. WorkManager persists work, survives reboots, supports constraints and retries, but it is deferrable and each run gets about 10 minutes. For short urgent work I use expedited WorkManager work instead of a service.
Senior
I choose by what the user expects. If they pressed Start and watch progress, a foreground service, or for media the Media3 MediaSessionService, which handles the foreground state for me. If they only expect the result eventually, WorkManager, which can itself run as a foreground service with setForeground for long work. The decision also has to survive policy: Play requires a justification per type, and background starts are mostly gone, so designs that start services from push or boot events need to move to WorkManager.
Learn it: Foreground services
What are the background start restrictions, and how do you handle them?
Junior
Since Android 12, an app in the background usually cannot start a foreground service. If it tries, the system throws an exception.
Mid
For apps targeting Android 12, startForegroundService from the background throws ForegroundServiceStartNotAllowedException. There are exemptions: a visible activity, the user interacting with a notification or widget, a high-priority FCM message, an exact alarm for a user-requested action, BOOT_COMPLETED, or the app being exempt from battery optimisation. Otherwise you use WorkManager, often expedited work.
Senior
I audit every call site of startForegroundService and classify it: user action (safe), exempt background trigger (allowed but fragile, since exemptions shrink between releases, for example while-in-use types cannot start from the background and Android 15 removed boot starts for several types), or plain background (must move to WorkManager). I make sure failures are not swallowed, and I track ForegroundServiceStartNotAllowedException in crash reporting per Android version after each targetSdk bump.
Learn it: Foreground services
What is a notification channel and who controls its settings?
Junior
A channel groups notifications of one kind, like messages or promotions. Since Android 8.0 (API 26) every notification must use a channel, and the user can change or turn off each channel in Settings.
Mid
You create it with createNotificationChannel and give it an importance that controls sound, the status bar icon and heads-up display. On API 26+ the channel importance replaces the notification's priority. After creation the user owns the settings: calling createNotificationChannel again can update the name and description, and can lower importance if the user has not touched it, but it can never raise importance.
Senior
I design channels around what users want to control separately, for example messages, order updates and promotions, because a single channel forces users to mute everything. Ids are stable constants. When a release must make a channel louder, I create a new id, migrate and delete the old one, knowing that deleted channels stay visible as a count in settings, so I avoid doing that often. I read getNotificationChannel(id).importance to see whether the user has muted a channel and adjust the in-app UI.
Learn it: Notifications and channels
How do you handle the POST_NOTIFICATIONS permission on Android 13?
Junior
On API 33+ you request POST_NOTIFICATIONS at runtime with ActivityResultContracts.RequestPermission(). If the user denies it, the app cannot show notifications.
Mid
Apps targeting 33 start with notifications off on new installs. notify() does not throw when the permission is missing; it just posts nothing, so I check the permission or areNotificationsEnabled() and show the information in the app instead. After two denials the system stops showing the dialog, so I send the user to the app notification settings with ACTION_APP_NOTIFICATION_SETTINGS.
Senior
I ask in context, after an action that makes the value clear, and use shouldShowRequestPermissionRationale to decide between explaining and sending to settings. Foreground-service and media notifications are a special case: the service still runs without the permission, but its notification only appears in the Task Manager. I track the grant rate per entry point in analytics and test a fresh install and an upgrade separately, because upgraded apps may have the permission pre-granted.
Learn it: Notifications and channels
What PendingIntent flags are required on Android 12 and why?
Junior
On API 31+ you must pass FLAG_IMMUTABLE or FLAG_MUTABLE when you create a PendingIntent. Immutable means the receiving app cannot change the intent.
Mid
Apps targeting 31 get an IllegalArgumentException if neither flag is set. Immutable is the safe default because another app that receives your PendingIntent cannot fill in fields of the intent. Mutable is needed when the system must add data at send time, such as an inline reply with RemoteInput, bubbles, or location and geofencing callbacks.
Senior
A mutable PendingIntent with an implicit intent is a security risk, because a receiver can redirect it, so on target 34 the system throws for that combination. I make every mutable PendingIntent explicit and comment why it is mutable. I also watch PendingIntent identity: the system matches on the intent (action, data, component, categories, not extras) and the request code, so FLAG_UPDATE_CURRENT with a shared request code makes several notifications open the same item.
Learn it: Notifications and channels
How do you group notifications, and what changed for full-screen intents in Android 14?
Junior
You call setGroup with the same key on each notification and post a summary notification with setGroupSummary(true). The system shows them together as one expandable group.
Mid
The summary carries the collapsed view, for example '3 new messages' with InboxStyle, and is what older versions show. On Android 7+ the system bundles the children under it, and it can also auto-group several notifications from an app that does not set a group. Full-screen intents launch an activity over the lock screen for calls and alarms; on Android 14 only calling and alarm apps get that by default.
Senior
For grouping I keep the summary in sync: update it when a child is added and cancel it when the last child is removed, or the shade shows an empty group. For full-screen intents I check NotificationManager.canUseFullScreenIntent() on Android 14, link to ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT if the feature really needs it, and fall back to a high-importance notification. Play policy decides who keeps the permission by default, so I would not build a non-calling feature on it.
Learn it: Notifications and channels
When would you choose AlarmManager over WorkManager?
Junior
AlarmManager is for something at a specific time, like a reminder or an alarm clock. WorkManager is for background work that must finish but can run later, like sync or uploads.
Mid
An alarm fires a PendingIntent at a chosen time, and exact alarms fire on time even in Doze with setExactAndAllowWhileIdle or setAlarmClock. But alarms are cleared on reboot, have no retry or constraints, and exact ones need special access on Android 12+. WorkManager persists, retries and survives reboot, but runs late by design and periodic work has a 15-minute minimum.
Senior
I ask what the user was promised. A time on the clock means an alarm, and when it fires the receiver posts the notification or enqueues WorkManager work for anything heavy. 'Eventually' means WorkManager. I also plan for exact access being denied, which is the default for most new installs on Android 14: the feature must still work inexactly and explain how to get exact timing. And I make the schedule data-driven (stored in Room) so reboot, time changes and permission grants all reschedule from the same source.
Learn it: Alarms and exact timing
What happens to alarms after a reboot, and how do you handle it?
Junior
All alarms are cleared. You add a receiver for BOOT_COMPLETED with the RECEIVE_BOOT_COMPLETED permission and schedule them again.
Mid
The receiver needs the stored list of alarms, so I keep the schedule in Room or DataStore. The receiver should not do database work on the main thread; it can enqueue a worker that reads the reminders, computes the next fire time for each and schedules them. Alarms are also cleared on force-stop, and the app only gets BOOT_COMPLETED after the user unlocks the device the first time, unless it is direct-boot aware.
Senior
I recompute from rules, not from stored timestamps: a reminder 'every day at 09:00' gets the next 09:00 after now, and missed ones are either dropped or shown once as missed, depending on the product. The same reschedule path handles TIME_SET, TIMEZONE_CHANGED and the exact-alarm permission broadcast, so there is one place to test. On Android 15 a boot receiver cannot start several foreground service types, so the reschedule must stay lightweight work, not a service.
Learn it: Alarms and exact timing
A user on Android 14 says exact reminders never fire. What do you check?
Junior
Whether the app has exact-alarm access. On Android 14 SCHEDULE_EXACT_ALARM is off by default for new installs, and the user must turn it on in Settings.
Mid
I check canScheduleExactAlarms(). If it is false, setExact throws SecurityException, so I look for a swallowed exception. Then I check that the alarm survived: a reboot or force-stop clears alarms, and a new alarm with an equal PendingIntent replaces an older one. adb shell dumpsys alarm shows which alarms are actually scheduled for the package.
Senior
I also check the delivery side: the receiver must be in the manifest with the right component, notifications must be allowed (POST_NOTIFICATIONS on Android 13+) and the channel not muted, or the alarm fires and nothing is visible. Restrictive battery settings and some OEM battery managers can still delay or block alarms, so I log the scheduled and actual fire times. Long term, the app listens for ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED so a later grant fixes existing reminders without the user editing them.
Learn it: Alarms and exact timing
When do you use RTC versus ELAPSED_REALTIME?
Junior
RTC uses the wall clock, so it is for times like 09:00. ELAPSED_REALTIME counts from boot and is for delays like 'in 30 minutes'.
Mid
ELAPSED_REALTIME ignores clock and timezone changes, so a 30-minute timer stays 30 minutes. RTC fires when the wall clock reaches the value, which is what a calendar reminder needs. Only the _WAKEUP variants wake a sleeping device; neither variant bypasses Doze.
Senior
For wall-clock reminders, the stored value should be the rule (local time and zone), not a millisecond timestamp, because a timezone change keeps the UTC instant fixed and the reminder would fire at the wrong local time. I compute the next occurrence with java.time in the current zone, which also handles daylight-saving gaps, and reschedule on TIMEZONE_CHANGED and TIME_SET. For timers I use ELAPSED_REALTIME_WAKEUP, and if a timer must survive reboot I store its wall-clock end time, because elapsed time restarts at boot.
Learn it: Alarms and exact timing
What is the difference between a manifest-declared and a context-registered receiver?
Junior
A manifest receiver is declared in AndroidManifest.xml, and the system can start the app to deliver the broadcast. A context-registered receiver is registered in code with registerReceiver and only works until you call unregisterReceiver.
Mid
Since Android 8 (target 26), manifest receivers get only explicit broadcasts and a short exemption list, like BOOT_COMPLETED, LOCALE_CHANGED and TIMEZONE_CHANGED. Context-registered receivers can get implicit broadcasts, but only while registered. On target 34, registerReceiver needs RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED; manifest receivers use android:exported, which is required when there is an intent filter since target 31.
Senior
I pick the manifest only when the app must react while not running, and keep that receiver tiny: it validates the action and enqueues WorkManager work. Everything that only matters while the UI is up is registered in code and tied to the lifecycle. I treat every exported receiver as a public API: other apps can send it intents, so I validate input, and use android:permission or a signature permission when only my apps should send. For events inside one app I use flows instead of broadcasts.
Learn it: Broadcast receivers
How do you do work in response to a broadcast without causing ANRs?
Junior
onReceive runs on the main thread, so you must not do network or database work there. You move the work to a background thread.
Mid
For a few seconds of work I call goAsync(), which returns a PendingResult, run the work on Dispatchers.IO and call finish() in a finally block. The broadcast still has to finish in about 10 seconds. For anything longer or anything that should retry, I enqueue a WorkManager request from onReceive and return.
Senior
The key point is process lifetime: after onReceive returns the receiver is not an active component, so the system can kill the process and any work I started. goAsync keeps the broadcast active only for the short limit, so I wrap the work in withTimeout. For heavy or retryable work, WorkManager is the right owner, and it cannot be blocked by the Android 15 rule against starting some foreground service types from BOOT_COMPLETED. I check ANR clusters in Play Console for receiver stacks after each release.
Learn it: Broadcast receivers
Why did implicit broadcasts stop reaching manifest receivers, and what do you use instead?
Junior
From Android 8, apps cannot declare manifest receivers for most implicit broadcasts, to save battery, because each broadcast used to wake many apps.
Mid
Exempt broadcasts like BOOT_COMPLETED, TIME_SET and LOCALE_CHANGED still work, as do explicit broadcasts and ones sent only to your app, like MY_PACKAGE_REPLACED. CONNECTIVITY_ACTION had already stopped for manifest receivers on target 24. The replacements are context-registered receivers while the app runs, or dedicated APIs: NetworkCallback for connectivity and WorkManager constraints for 'when online' or 'when charging'.
Senior
The receiver does not crash; it just never fires, so these bugs show up as missing data. When raising targetSdk I review the merged manifest, including receivers that libraries add, against the exemption list. I also prefer modelling conditions rather than events: instead of listening for 'network came back', I enqueue work with a network constraint, which also survives process death and reboot.
Learn it: Broadcast receivers
What changed for receivers in Android 14, and how do you choose the export flag?
Junior
Apps targeting Android 14 must pass RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED when they call registerReceiver, or the app crashes with a SecurityException.
Mid
The flag is required unless the receiver only listens for system broadcasts. NOT_EXPORTED means only my app and the system can send to it, so I use it for my own actions; EXPORTED is for broadcasts from other apps. ContextCompat.registerReceiver takes the flag on every version. A common trap is DownloadManager.ACTION_DOWNLOAD_COMPLETE, which comes from another process and needs EXPORTED.
Senior
Android 14 also queues broadcasts to context-registered receivers while the app is cached and may merge repeats, so background delivery is not real-time. Together with the export rule, that pushes design toward fewer receivers: internal events become flows, system conditions become WorkManager constraints, and the remaining exported receivers are reviewed like public endpoints, with input validation and, where possible, a sender permission.
Learn it: Broadcast receivers

Testing basics

What is the difference between a mock and a fake?
Junior
A mock is a test double that you script with stubs and that records which methods were called and with what arguments. A fake is a simplified working implementation that keeps in-memory state, like a MutableMap-backed repository.
Mid
Mocks let you check interactions: what was called, how often, with which arguments. Fakes let you check outcomes through state. A default MockK mock throws for any call you did not stub, so every call the SUT makes needs a stub. A fake needs no stubs because it actually stores and returns data.
Senior
The choice affects how brittle tests are. Mock-heavy tests encode the SUT's call sequence, so a refactor that changes internal calls breaks them even when behaviour is the same. Fakes couple to behaviour and survive those refactors, and one fake can be shared across many test classes. I default to fakes for repositories and data sources, and use mocks for interaction contracts with things I cannot observe through state, such as analytics or a payment SDK, checked with an exact count and confirmVerified.
Learn it: Unit tests with JUnit and MockK
When do you use coEvery instead of every?
Junior
coEvery is for suspend functions and every is for regular functions. Calling a suspend function inside every does not compile.
Mid
The every block is a normal lambda, so it cannot call a suspend function. coEvery takes a suspend lambda, so the stubbed call can be a suspend call, and the same applies to coVerify versus verify. The test itself also needs a coroutine to call the SUT, which is what runTest provides.
Senior
Beyond the syntax, coEvery has suspend-aware answers: coAnswers lets a stub suspend, for example to delay inside runTest's virtual time or to return a value computed by another suspend call. For a suspend repository with real behaviour I would rather write a fake, and keep coEvery for one-off stubs and failure injection, like coEvery { api.load() } throws IOException().
Learn it: Unit tests with JUnit and MockK
What does relaxed = true do, and when is it dangerous?
Junior
It makes MockK return simple default values, like 0, false or an empty string, for any function you did not stub, instead of throwing an exception.
Mid
The danger is that a missing stub silently returns a placeholder, so a test can pass on a code path you never really set up. For example, a relaxed PaymentGateway returns an empty string for an unstubbed getTransactionId(), and the test passes even though no one checked what happens with a real id. Reference types get chained mocks, which hide even more.
Senior
I use a strict mock by default so a missing stub fails loudly and names the call. When the noise is Unit functions like log or track, relaxUnitFun = true relaxes only those, and value-returning calls must still be stubbed. If a test needs many stubs either way, that dependency usually wants a fake. Relaxed mocks are fine for collaborators the test really does not care about, as long as the test asserts on something that would fail if the placeholder value leaked into the result.
Learn it: Unit tests with JUnit and MockK
How do you structure a test that uses arrange-act-assert?
Junior
You set up the inputs and mocks, call the method under test, then check the output with assertions. Each section is separated by a blank line or a comment.
Mid
Arrange creates the SUT and stubs or fills its dependencies. Act calls the single method or function you are testing. Assert checks the return value and the side effects, with verify or coVerify for mocks or by reading a fake's state. Keeping the three sections visually separate makes a failing test quick to understand.
Senior
I keep one behaviour per test and name the test after it, so a failure message reads like a broken requirement. When arrange code repeats, I move it into small builders or shared fakes rather than a big @Before, so each test still shows the data that matters. A long arrange section is a design signal that the SUT has too many dependencies. And I make sure the assertions would actually fail if the behaviour broke, for example by briefly breaking the code once to see the test go red.
Learn it: Unit tests with JUnit and MockK
What is the difference between StandardTestDispatcher and UnconfinedTestDispatcher?
Junior
StandardTestDispatcher queues coroutines, and they run when the test suspends or calls runCurrent or advanceUntilIdle. UnconfinedTestDispatcher starts new coroutines immediately. StandardTestDispatcher is the default inside runTest.
Mid
StandardTestDispatcher gives control over order, so you can check a Loading state before advancing to Success. UnconfinedTestDispatcher runs a new coroutine eagerly until its first suspension, which is convenient for a background collector that should be subscribed before the test continues. Both use virtual time, and they must share the test's scheduler to stay in step.
Senior
I default to StandardTestDispatcher, often installed as Main through a MainDispatcherRule, because it behaves predictably and lets me assert intermediate states. I use UnconfinedTestDispatcher narrowly, for example for a backgroundScope collector, since eager execution can hide ordering bugs: code that relies on something running before the next line passes in tests and races in production. Neither matches Dispatchers.Main.immediate exactly, so I assert on the states the UI cares about rather than on exact scheduling. And I make sure every dispatcher in the test shares one TestCoroutineScheduler, otherwise advancing one clock does nothing for the other.
Learn it: Testing coroutines and flows
Why does a stateIn(WhileSubscribed) flow not emit in a test?
Junior
WhileSubscribed only starts the upstream flow when someone collects the StateFlow. If the test only reads .value without collecting, it sees just the initial value.
Mid
stateIn launches its sharing coroutine in the given scope, usually viewModelScope, and with WhileSubscribed it waits for the first subscriber. So the test needs Dispatchers.setMain for viewModelScope and an active collector: Turbine's test block, or a collector in backgroundScope. With a StandardTestDispatcher the sharing coroutine is queued, so the collector also has to let the scheduler run, which happens when awaitItem suspends or after runCurrent.
Senior
I test the StateFlow the UI actually uses, with a collector, instead of testing the upstream flow alone, so the initial value, the catch and the sharing strategy are covered too. The 5-second stop timeout uses virtual time, so I can test that upstream stops after the last collector leaves with advanceTimeBy(5_000) and runCurrent. I do not switch production code to SharingStarted.Eagerly to make tests easier; the test should adapt to the production behaviour.
Learn it: Testing coroutines and flows
How do you test a suspend function that uses a dispatcher and delays?
Junior
Call it inside runTest, with the dependencies replaced by fakes or MockK stubs using coEvery, and assert on the result.
Mid
The class should take its dispatcher as a constructor parameter. In the test I pass StandardTestDispatcher(testScheduler), so withContext runs on the test scheduler and any delay is skipped in virtual time. A hard-coded Dispatchers.IO would run on a real thread, the delays would take real time, and timing assertions would be unreliable.
Senior
With the dispatcher injected I can test timing exactly: launch the call, advanceTimeBy to just before a retry, check that only one attempt happened, then runCurrent at the retry time and check the second. testScheduler.currentTime tells me how much virtual time passed. I keep failure cases in fakes or coEvery throws, and I check that cancellation still propagates, for example that a catch block does not swallow CancellationException.
Learn it: Testing coroutines and flows
What happens if you forget Dispatchers.resetMain?
Junior
Dispatchers.Main stays replaced with your test dispatcher for later tests in the same JVM, so they can behave unexpectedly.
Mid
setMain changes global state for the whole process. A later test that does not set Main itself gets the old test dispatcher, tied to a previous test's scheduler, so its coroutines may never run and the failure depends on test order. Putting setMain and resetMain in a JUnit rule means cleanup runs even when a test fails.
Senior
I use one MainDispatcherRule everywhere, built on TestWatcher with starting and finished, so no test touches setMain by hand. Because runTest picks up the Main test dispatcher's scheduler, the rule also keeps all dispatchers on one clock. Gradle can run test classes in separate forked JVMs, which limits the damage, but that is not a fix; the cleanup belongs in the rule.
Learn it: Testing coroutines and flows
How do you structure a unit test for a ViewModel?
Junior
Put the test in src/test so it runs on the JVM. Create a fake repository that returns a known value, create the ViewModel, call its method, and check the resulting state with JUnit 4 assertions.
Mid
A MainDispatcherRule replaces Dispatchers.Main with a StandardTestDispatcher so viewModelScope works on the JVM. Inside runTest I call the ViewModel method, assert Loading while the launched coroutine is still queued, then call advanceUntilIdle() and assert Success or Error on the public StateFlow.
Senior
I keep the ViewModel's dependencies behind interfaces with fakes, inject dispatchers into lower layers, and use one shared MainDispatcherRule so no test manages setMain by hand. I test each state transition the UI depends on, including errors, retries and process-death restoration through SavedStateHandle, which can be constructed directly in a test. How I observe state depends on how it is built: .value for a MutableStateFlow, a collector for stateIn(WhileSubscribed), Turbine for one-off events.
Learn it: ViewModel tests
When do you use a fake instead of a mock (MockK)?
Junior
A fake is a real class that implements the interface with simple in-memory behaviour. A mock is created by MockK and is scripted with stubs. For a repository I use a fake.
Mid
A fake is better when the dependency has behaviour or state, like a repository, because the test just sets data and reads results. A mock with coEvery and coVerify is better when the test is about the interaction, like checking that a tracker was called exactly once with an event.
Senior
Fakes test behaviour and survive refactors that change which methods the ViewModel calls; mock-heavy tests encode call sequences and break on harmless changes. A shared fake, kept in a test fixtures module, is written once and reused by every screen's tests. Relaxed mocks are the worst of both: they return placeholders for calls nobody set up, so a test can pass on a path it never exercised. I still use mocks for things I cannot observe through state, such as analytics or a third-party SDK.
Learn it: ViewModel tests
How do you handle coroutines in a ViewModel test?
Junior
Use runTest from kotlinx-coroutines-test, which gives virtual time, and call advanceUntilIdle() to run the pending coroutines.
Mid
viewModelScope uses Dispatchers.Main, so a MainDispatcherRule sets it to a StandardTestDispatcher before each test and resets it afterwards. runTest reuses that scheduler. Because StandardTestDispatcher queues coroutines, I call runCurrent() or advanceUntilIdle() before asserting. UnconfinedTestDispatcher runs them eagerly, which is simpler but hides the Loading state and ordering problems.
Senior
viewModelScope cannot be injected, but everything below the ViewModel can, so repositories take their IO dispatcher as a constructor parameter and the test passes a test dispatcher on the same scheduler. Any delay, debounce or retry then runs in virtual time and I can step through it with advanceTimeBy and runCurrent. There is no public way to clear a ViewModel from a test, so I do not rely on onCleared to finish work; cleanup logic I care about lives in a class I can test directly.
Learn it: ViewModel tests
How do you test a StateFlow that the UI collects?
Junior
Call the ViewModel method, advance the scheduler, and check viewModel.uiState.value.
Mid
For a MutableStateFlow exposed with asStateFlow(), .value is always current, so I assert on it after advancing. For a state built with stateIn(WhileSubscribed), there is no upstream until something collects, so I collect it with Turbine's test block or a backgroundScope collector before asserting.
Senior
I also assert the initial value, because the UI renders it first. StateFlow is conflated and skips equal values, so with Turbine I may not see every intermediate state if the producer is faster than the collector; with a StandardTestDispatcher I can check Loading explicitly before advancing. And I make sure the test reads only the public read-only StateFlow, so it checks the contract rather than how the ViewModel stores state.
Learn it: ViewModel tests
How does Compose UI testing differ from Espresso?
Junior
Compose UI tests use a compose test rule and query the semantics tree, while Espresso finds views in the View hierarchy. You write onNodeWithText or onNodeWithTag instead of onView(withId(...)).
Mid
Composables are not Views, so there are no view IDs; tests find nodes through semantics like text, content description and test tags. The semantics tree can be merged, so children of a Button or a mergeDescendants parent are not separate nodes unless you pass useUnmergedTree = true. Like Espresso, the rule synchronizes automatically, waiting for Compose to be idle before each action and assertion.
Senior
Both APIs work together in a hybrid screen: the compose rule also drives Espresso, and Espresso idling resources are honoured by Compose tests. The big differences are synchronization and time: Compose tests run on a virtual mainClock that I can pause with autoAdvance = false to step through animations, and waitUntil covers work outside Compose. Because tests use the same semantics as TalkBack, writing them often exposes missing content descriptions, so good tests and good accessibility tend to go together.
Learn it: Compose UI tests
What is the semantics tree and why does it matter for tests?
Junior
It is a description of the UI that accessibility services use, with properties like text, role and click actions. Compose UI tests find and check nodes through it instead of through pixels or views.
Mid
Finders search the merged tree by default. When a parent merges its descendants, its children's texts are combined into the parent node, but their test tags are not, so a child tag is not found and a text finder returns the parent. useUnmergedTree = true searches the tree with every child as its own node.
Senior
Merging decides what accessibility users get as one focusable item, so I treat the merged tree as the user-facing contract and assert on it where possible, for example that a card reads as Coffee, 3.50 and has a click action. I drop to the unmerged tree only for details that are not part of that contract. When a finder misbehaves I print the tree with printToLog on onRoot(), or with useUnmergedTree to compare, instead of guessing.
Learn it: Compose UI tests
How do you test async UI updates in Compose?
Junior
Use rule.waitUntil with a timeout and a condition that returns true when the UI is ready, never Thread.sleep.
Mid
The rule already waits for recomposition, layout and animations before each finder and assertion, so state changes usually need no waiting code. For work outside Compose, like a repository on a background thread, waitUntil polls a Boolean condition, for example that onAllNodesWithTag("content").fetchSemanticsNodes() is not empty, until it is true or the timeout passes.
Senior
I prefer removing the async work from UI tests: give the composable its state directly, or a ViewModel with a fake repository, so the UI test checks rendering and events and the coroutine logic is covered by runTest in a JVM test. For time-based UI, like a delayed LaunchedEffect or an animation, I set mainClock.autoAdvance = false and step with mainClock.advanceTimeBy. For real background work I can't avoid, I register an IdlingResource so every assertion waits for it, rather than scattering waitUntil calls.
Learn it: Compose UI tests
When should you use testTag versus onNodeWithText?
Junior
Use onNodeWithText when the text is visible and stable. Use testTag when the node has no text, like an icon, a container or a list, or when the text changes.
Mid
Text finders check what the user actually sees, but break when copy or language changes; reading the text from the same string resource avoids that. testTag is a fixed id that does not depend on user-facing text, which suits containers, lists and fields whose content varies.
Senior
Finding by text or content description also checks that the UI is understandable to a user or a screen reader, so I prefer it for buttons and labels and load the strings from resources. I use testTag for structure the user does not read, like a list or a card container. Test tags are not read by accessibility services; they are only exposed to UI Automator if testTagsAsResourceId is turned on. Overusing tags can let a test pass even when the visible label is wrong, so I avoid tagging something just to dodge a text assertion.
Learn it: Compose UI tests