Interview frequency: …
Short answer
A cold flow (Flow) does not execute its code until there is a consumer (collector), while a hot flow (StateFlow/SharedFlow) broadcasts data in memory at all times even if there is no listener.
Explanation
A cold flow is like a CD that makes no sound until a specific listener plays it, and each new consumer starts the sequence from scratch (such as a database query). A hot flow is like a live radio broadcast; it lives independently in memory and shares the same data with several listeners at once (multicasting) and keeps the last value (StateFlow) or a replay cache (SharedFlow).
Code example
// Cold Flow: Starts from scratch with each collect()
fun getNumbers(): Flow<Int> = flow {
emit(1); emit(2)
}
// Hot Flow: Retains state in memory and emits it to current observers
val stateFlow = MutableStateFlow("Initial Value")Common mistakes
- Converting a cold flow to a hot flow using shareIn or stateIn without specifying a CoroutineScope and a suitable SharingStarted policy, causing a leak in data consumption.