Flow Context, Errors & Backpressure
KOTLIN › Flow
Which dispatcher a flow stage runs on, where failures can be caught, and what happens when the producer outruns the collector.
These three concerns share one theme: who is running, and what happens when the two ends of a pipeline disagree. Interviewers probe them because the mistakes are specific and recognisable: withContext inside a flow builder, a catch placed too high to see the failure, and a conflate silently fused away by a following buffer. Strong answers explain context preservation as a guarantee the library enforces rather than a convention, and can contrast Flow suspension-based backpressure with the request(n) protocol reactive-streams libraries use.
What this covers
- Context preservation: the collect lambda runs in its caller context, and the flow may not change that
- withContext inside flow { } throws "Flow invariant is violated"; flowOn is the supported way to move the producer
- flowOn affects only what is above it, and inserts a channel, so it implies buffer
- Exception transparency: never wrap emit in your own try/catch; recover with the catch operator
- catch sees the producer and operators above it only, never the collect lambda
- retry re-collects the entire upstream, so producer side effects repeat; retryWhen adds the attempt index for backoff
- Backpressure comes free from emit suspending: no request(n), no overflow strategy, nothing dropped by default
- BufferOverflow is SUSPEND, DROP_OLDEST (which is what conflate is) or DROP_LATEST
- conflate drops values but lets the collector finish; collectLatest cancels the collector mid-work
- Adjacent flowOn/buffer/conflate fuse into one channel config, so a later buffer silently removes an earlier conflate
Study this topic
- Flow Context, Errors & Backpressure explained: the guided lesson
- 18 practice quiz questions
- 13 revision flashcards
- Flow Context, Errors & Backpressure interview questions and answers