Flows
Explore Kotlin flows as cold asynchronous streams implementing the Observable design pattern. Understand how to publish and subscribe to data using emit and collect functions. Learn about flows properties like backpressure and concurrency, plus how to enhance them with buffering and conflation for efficient data processing.
We'll cover the following...
Flows
A flow is a cold, asynchronous stream and is an implementation of the Observable design pattern.
As a quick reminder, the Observable design pattern has two methods: subscribe() (which allows consumers to, well, subscribe for messages) and publish() (which sends a new message to all of the subscribers).
The publish method of the Flow object is called emit(), while the subscribe method is called collect().
We can create a new flow using the flow() function:
val numbersFlow: Flow<Int> = flow { ... }
Inside the flow constructor, we can use the emit() function to publish a new value to all listeners.
For example, here we create a flow that would publish ten numbers using the flow constructor:
flow {(0..10).forEach {println("Sending $it")emit(it)}}
Now that we’ve covered how to publish a message, let’s discuss how to subscribe to a flow.
For that, we can use the collect() function available ...