Flows
A Flow in Kotlin is a cold, asynchronous stream that implements the Observable design pattern, which we explored in Chapter 4, Getting Familiar with Behavioral Patterns.
To refresh your memory, the Observable design pattern typically provides two methods: subscribe()
for consumers to subscribe to messages, and publish()
to broadcast a new message to all subscribers. In the case of a Kotlin Flow, these methods are renamed to collect()
and emit()
respectively.
You can instantiate a new flow using the flow()
builder function:
val numbersFlow: Flow<Int> = flow {
...
}
Within the flow constructor, you can utilize emit()
to send new values to all subscribers. For instance, let’s create a flow that emits ten numbers:
flow {
(0..10).forEach {
println("Sending $it")
emit(it)
}
}
To subscribe to a flow, you use the collect()
method on the flow object:
runBlocking {
numbersFlow.collect { number ->
...