Kotlin Flow
Kotlin Flow
Kotlin Flow is a part of Kotlin Coroutines used to handle asynchronous streams of data.
It is especially useful when you want to emit multiple values over time, such as:
-
Live data updates
-
Database changes
-
Network streaming
-
User input events
Think of Flow as a cold, asynchronous data stream.
1. Why Use Kotlin Flow?
Without Flow:
-
Callbacks → messy
-
LiveData → Android-only
-
RxJava → complex
With Flow:
-
✅ Simple & readable
-
✅ Built on coroutines
-
✅ Backpressure handling
-
✅ Platform independent
2. Basic Flow Example
Output:
3. Key Flow Terms
| Term | Meaning |
|---|---|
Flow |
Stream of data |
emit() |
Send value |
collect() |
Receive value |
flow {} |
Builder |
suspend |
Async support |
4. Cold Flow (Important Concept)
Flow is cold, meaning:
-
It starts emitting only when collected
-
Each collector gets a new flow
➡ "Flow started" prints twice
5. Flow Builders
flow
flowOf
asFlow
6. Operators in Flow
map
filter
take
7. Flow Context (flowOn)
8. Exception Handling in Flow
9. onStart & onCompletion
10. Terminal Operators
| Operator | Purpose |
|---|---|
collect |
Consume data |
toList |
Convert to list |
first |
Get first value |
single |
Expect one value |
11. Flow vs Suspend Function
| Suspend Function | Flow |
|---|---|
| Returns one value | Emits many values |
| One-time result | Continuous stream |
12. Real-Life Example (Android / Backend)
Summary
-
Flow = async data stream
-
Cold by default
-
Built on coroutines
-
Powerful operators
-
Cleaner than RxJava
