Flow: the Basics Interview Questions

KOTLIN › Flow

What is a Kotlin Flow, and how is it different from a suspend function?

What a strong answer covers: A suspend function returns a single value; a Flow emits many values over time, asynchronously. A Flow is a cold stream: the code in flow { } doesn't run until someone calls a terminal operator like collect, and runs again for each collector. Use Flow for things like database observation, location updates or a search query stream.

What does it mean that a Flow is cold? How is that different from a hot stream?

What a strong answer covers: A cold flow starts producing only when collected and each collector gets its own independent run, like calling the function again. A hot stream such as StateFlow or SharedFlow is active regardless of collectors and all collectors share the same emissions. A cold flow from Room re-queries per collector; sharing it requires stateIn or shareIn.

What are intermediate and terminal operators? Give examples of each.

What a strong answer covers: Intermediate operators like map, filter, onEach, debounce and flatMapLatest return a new Flow and don't run anything. Terminal operators like collect, first, toList, single and launchIn are suspend functions (except launchIn) that start the flow and consume values. Nothing happens until a terminal operator is called.

How do you expose data from Room through a repository to a ViewModel and then the UI with Flow? Where do threading decisions live?

What a strong answer covers: Room DAO returns Flow<List<Entity>>, already main-safe and re-emitting on table changes. The repository maps entities to domain models with map. The ViewModel converts to UI state and calls stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), initial). The UI collects with collectAsStateWithLifecycle or repeatOnLifecycle. Threading lives in the data layer: flowOn(Dispatchers.Default) for heavy mapping, never in the UI.

What are the rules a flow builder must follow, like context preservation and exception transparency, and what breaks if you violate them?

What a strong answer covers: Context preservation: a flow must emit in the collector's context, so you can't call emit from inside withContext or another coroutine; doing so throws IllegalStateException. Use flowOn to change upstream context or channelFlow to emit from several coroutines. Exception transparency: you shouldn't catch an exception from downstream and keep emitting; use the catch operator, which only sees upstream exceptions. These rules make flows predictable to compose.

Back to Flow: the Basics