0
0
KotlinConceptBeginner · 3 min read

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.

kotlin
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")
    }
}
Output
Received 1 Received 2 Received 3
🎯

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, and collect to work with data streams.

Key Takeaways

Flow represents a stream of asynchronous values emitted over time.
It is cold and starts emitting only when collected.
Use Flow to handle multiple events like user input or network updates without blocking.
Flow works seamlessly with Kotlin coroutines for easy asynchronous code.
Operators let you transform and process data streams efficiently.