Middle
What is the difference between hot and cold streams?
sobes.tech AI
Answer from AI
Hot streams:
- Active regardless of observers.
- Always emit the latest available data to subscribers from the moment of subscription.
- Examples:
LiveData,StateFlow,SharedFlow.
Cold streams:
- Active only when there is at least one observer.
- Execute logic upon each new subscription.
- Examples:
Flow,Sequence.
StateFlow is a specialized SharedFlow that remembers the last value.
SharedFlow can be configured to work like StateFlow with a replay buffer of 1.
Key differences:
| Operation | Hot stream | Cold stream |
|---|---|---|
| Activity | Always | On subscription |
| Logic execution | Once | On each subscription |
| State retention | Yes (LiveData, StateFlow, SharedFlow with replay) | No (by default) |
| Multi-user | Yes | No (each subscriber gets a separate copy) |
Hot streams are used to represent UI state or shared data. Cold streams are for performing operations upon subscription, such as network requests or database queries.
Example of a cold stream:
// This stream will load data only when there is a subscriber
fun loadData(): Flow<Data> = flow {
// Data loading occurs here
emit(NetworkApi.getData())
}
Example of a hot stream (StateFlow):
// This stream always has a value and is available for subscription
val uiState: StateFlow<UiState> = MutableStateFlow(LoadingUiState)
fun updateState(newState: UiState) {
uiState.value = newState
}