What is Flow in Kotlin: Explained with Examples
Flow in Kotlin is a type that represents a stream of values that are computed asynchronously. It allows you to handle multiple values over time, like a sequence of events, using a simple and safe way to work with asynchronous data.How It Works
Imagine you are watching a series of live sports scores updating on your phone. Instead of getting all scores at once, you receive updates one by one as they happen. Flow works similarly by delivering values over time asynchronously.
Under the hood, Flow is like a conveyor belt that produces data items one after another. You can collect these items as they come, without blocking your program. This makes it great for handling streams of data like user inputs, network responses, or sensor readings.
Example
This example shows a simple Flow that emits numbers from 1 to 3 with a delay between each. We collect and print each number as it arrives.
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun simpleFlow(): Flow<Int> = flow { for (i in 1..3) { delay(100) // simulate work emit(i) // emit next value } } fun main() = runBlocking { simpleFlow().collect { value -> println("Received $value") } }
When to Use
Use Flow when you need to handle multiple asynchronous values over time, such as:
- Listening to user actions like clicks or text input
- Receiving updates from a network or database
- Processing sensor data or real-time events
It helps keep your app responsive by not blocking the main thread while waiting for data.
Key Points
- Flow is cold, meaning it starts producing values only when collected.
- It supports suspending functions and can emit multiple values asynchronously.
- It integrates well with Kotlin coroutines for easy asynchronous programming.
- Use operators like
map,filter, andcollectto work with data streams.