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

import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*
fun simpleFlow(): Flow<Int> = flow {
for (i in 1..3) {
delay(1000)
emit(i)
}
}

fun main() = runBlocking {
simpleFlow().collect { value ->
println(value)
}
}

Output:

1
2
3

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

val flow = flow {
println("Flow started")
emit(1)
}
flow.collect { println(it) }
flow.collect { println(it) }

"Flow started" prints twice


5. Flow Builders

flow

flow { emit(1) }

flowOf

flowOf(1, 2, 3)

asFlow

listOf(1, 2, 3).asFlow()

6. Operators in Flow

map

flowOf(1, 2, 3)
.map { it * 2 }
.collect { println(it) }

filter

flowOf(1, 2, 3, 4)
.filter { it % 2 == 0 }
.collect { println(it) }

take

flowOf(1, 2, 3, 4)
.take(2)
.collect { println(it) }

7. Flow Context (flowOn)

flow {
emit("Data")
}.flowOn(Dispatchers.IO)

8. Exception Handling in Flow

flow {
emit(1)
throw Exception("Error")
}.catch {
emit(-1)
}.collect {
println(it)
}

9. onStart & onCompletion

flowOf(1, 2)
.onStart { println("Started") }
.onCompletion { println("Completed") }
.collect { println(it) }

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)

fun observeCounter(): Flow<Int> = flow {
var count = 0
while (true) {
emit(count++)
delay(1000)
}
}

Summary

  • Flow = async data stream

  • Cold by default

  • Built on coroutines

  • Powerful operators

  • Cleaner than RxJava

You may also like...