Flow Context, Errors & Backpressure Interview Questions
KOTLIN › Flow
What does flowOn do, and which part of the flow does it affect?
What a strong answer covers: flowOn changes the dispatcher for everything upstream of it (the builder and operators before it), not downstream. The collector still runs in its own context. Using it once near the source, like flowOn(Dispatchers.IO), keeps blocking work off the main thread while collection stays on Main.
How do you handle errors in a Flow? What does the catch operator catch and not catch?
What a strong answer covers: catch intercepts exceptions from upstream only, where you can emit a fallback value or error state, rethrow, or log. It doesn't catch exceptions thrown in operators after it or in the collect block; for those, wrap collect in try/catch or move the logic into onEach before catch. After catch, the original flow is finished.
What is backpressure, and what does buffer, conflate and collectLatest do about a slow collector?
What a strong answer covers: Backpressure is when the producer is faster than the consumer. By default a flow is sequential: emit suspends until the collector processes the value, so the producer slows down. buffer runs producer and collector in separate coroutines with a queue between them. conflate keeps only the latest value, dropping intermediate ones. collectLatest cancels the collector's previous work when a new value arrives. Choose based on whether every value matters.
How would you add retry with exponential backoff to a Flow that fetches from the network?
What a strong answer covers: retryWhen { cause, attempt -> if (cause is IOException && attempt < 3) { delay(1000L * 2.0.pow(attempt.toInt()).toLong()); true } else false }. Only retry transient errors (IOException, 5xx), never 4xx; cap attempts; add jitter so many clients don't retry in sync; and expose a loading or error state while retrying.
A flow that collects a fast sensor and writes each value to a database is falling behind and memory keeps growing. How would you diagnose and fix it?
What a strong answer covers: Growth suggests an unbounded buffer (buffer(UNLIMITED), callbackFlow with an unlimited channel, or a SharedFlow with a big replay) and a consumer slower than the producer. Options: conflate or sample(100ms) if only the latest matters, chunk writes into batched transactions with a bounded buffer and BufferOverflow.DROP_OLDEST, move the write onto a dedicated dispatcher, and measure with the profiler. A strong answer asks whether every sample must be kept before choosing to drop.