How to Use Flow in Android for Reactive Data Streams
In Android,
Flow is a Kotlin feature used to handle asynchronous streams of data in a reactive way. You create a Flow to emit values over time and collect them in your UI or other components using collect inside a coroutine.Syntax
A Flow is created using the flow {} builder which emits values with emit(). You collect values using collect {} inside a coroutine scope.
- flow {}: Defines the data stream.
- emit(value): Sends a value to the stream.
- collect {}: Receives values from the stream.
kotlin
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow fun simpleFlow(): Flow<Int> = flow { emit(1) emit(2) emit(3) }
Example
This example shows how to create a Flow that emits numbers and collect them in a coroutine to print each number.
kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun simpleFlow(): Flow<Int> = flow { emit(1) delay(100) // simulate work emit(2) delay(100) emit(3) } fun main() = runBlocking { simpleFlow().collect { value -> println("Received $value") } }
Output
Received 1
Received 2
Received 3
Common Pitfalls
Common mistakes when using Flow include:
- Not collecting the flow, so no data is emitted.
- Calling
collectoutside a coroutine scope, causing errors. - Blocking the main thread instead of using
runBlockingor proper coroutine scopes.
Always collect flows inside a coroutine and avoid blocking UI threads.
kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun wrongUsage() { val flow = flow { emit(1) } // This will not work because collect is not called inside coroutine // flow.collect { println(it) } } fun rightUsage() = runBlocking { val flow = flow { emit(1) } flow.collect { println(it) } }
Quick Reference
Remember these key points when using Flow in Android:
- Use
flow {}to create a flow. - Emit values with
emit(). - Collect values inside a coroutine with
collect {}. - Use
runBlockingor lifecycle-aware scopes in Android. - Flows are cold streams; they start emitting only when collected.
Key Takeaways
Use Kotlin Flow to handle asynchronous data streams reactively in Android.
Create flows with the flow builder and emit values using emit().
Always collect flows inside a coroutine scope to receive data.
Avoid blocking the main thread; use proper coroutine scopes for collection.
Flows are cold and start emitting only when collected.