A suspend function produces a single result. A Flow produces a sequence of values over time, asynchronously, and it is how Kotlin models anything that updates repeatedly: a database query that re-emits on change, location updates, search-as-you-type.
Flows are cold by default, meaning the producer block does not run until something collects, and it runs again for each collector. Collecting is itself a suspend operation, so a Flow is always consumed inside a coroutine and inherits that coroutine's cancellation - close the screen and the collection stops.
The operators mirror the collection ones - map, filter, take - but run in the coroutine world and can themselves suspend. Beyond those, the ones that matter in practice are debounce, which waits for a pause in emissions and is how you avoid a network call per keystroke; distinctUntilChanged, which drops consecutive duplicates; and flatMapLatest, which cancels the previous inner flow when a new value arrives.
StateFlow and SharedFlow are the hot variants. A StateFlow always holds a current value and emits it to every new collector, which makes it the standard way to expose UI state from a ViewModel - level five uses exactly this.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// A cold flow: nothing runs until it is collected
fun temperatures(): Flow<Int> = flow {
val readings = listOf(20, 20, 21, 23, 23, 26)
for (reading in readings) {
delay(100)
emit(reading)
}
}
fun main() = runBlocking {
temperatures()
.distinctUntilChanged() // drop consecutive duplicates
.filter { it > 20 }
.map { "${it}C" }
.collect { println(it) } // 21C, 23C, 26C
// StateFlow always has a current value
val state = MutableStateFlow("idle")
val watcher = launch {
state.take(2).collect { println("state: $it") }
}
delay(50)
state.value = "loading"
watcher.join()
}
Discussion
No questions on this topic yet. Sign in to ask the first one.