Channels & Channel-Backed Flows Interview Questions

KOTLIN › Flow

What is a Channel in Kotlin coroutines, and how is it different from a Flow?

What a strong answer covers: A Channel is a hot communication primitive between coroutines, like a suspending queue: send suspends if the buffer is full, receive suspends if it's empty. Each value is received by exactly one receiver (fan-out). A Flow is a cold, declarative stream re-run per collector. Channels are lower level; you usually expose them as flows with receiveAsFlow or consumeAsFlow.

What channel capacities are there, and how does each behave?

What a strong answer covers: RENDEZVOUS (0, default): send waits until a receiver takes it. BUFFERED: a default buffer of 64. A fixed number: a buffer of that size. CONFLATED: keeps only the latest value, send never suspends. UNLIMITED: never suspends, risks running out of memory. Overflow policies (SUSPEND, DROP_OLDEST, DROP_LATEST) can also be set.

What are callbackFlow and channelFlow, and why must callbackFlow end with awaitClose?

What a strong answer covers: Both build a flow backed by a channel so you can emit from callbacks or several coroutines. callbackFlow is for registering a listener: trySend from the callback and in awaitClose { unregister() } remove the listener. awaitClose suspends until the collector cancels, keeping the flow alive; without it the builder returns immediately and throws, and you'd leak the listener.

Model a producer-consumer pipeline, such as downloading a list of files with at most three at a time, using channels. How do you close and clean up correctly?

What a strong answer covers: A producer coroutine sends URLs into a Channel and closes it when done; three worker coroutines each loop with for (url in channel) and download; the loop ends when the channel is closed and empty. Run it all inside coroutineScope so cancellation and failures propagate; a worker failure cancels the rest unless supervised. Alternatives: a Semaphore(3) or flatMapMerge(concurrency = 3) are often simpler.

When would you choose a Channel over a SharedFlow for events, and what delivery guarantees does each actually give you?

What a strong answer covers: A Channel delivers each element to exactly one receiver and buffers while nobody is receiving, so events aren't dropped just because the UI is between collectors, but with several collectors each event goes to only one of them, and an event can still be lost if the collector is cancelled after receiving it. A SharedFlow broadcasts to all current subscribers and, without replay, drops emissions when there are none. Neither guarantees exactly-once to a UI that's being recreated, which is why the stronger answer is modelling events as state.

Back to Channels & Channel-Backed Flows