Exploring Different Ways to Collect Kotlin Flow
Simple app to demonstrate Kotlin flow(), emit(), collectAsState(), collect(), viewModelScope.launch(), launchWhenStarted() and repeatOnLifecycle()
This is part of the asynchronous flow series:
- Part 1 — Exploring Android LiveData Usages and Behaviors
- Part 2 — Introduction to Kotlin Flows and Channels
- Part 3 — Exploring Different Ways to Collect Kotlin Flow
- Part 4 — Convert Flow to SharedFlow and StateFlow
- Part 5 — Flow, SharedFlow, StateFlow Class Diagram
- Part 6 — Kotlin Flow — Combine, Merge and Zip
Basic Kotlin Flow Usages
You first need to create a flow before you can collect it.
Create Flow<T>
and Emit T
Value
1. Create Flow<T>
Using kotlinx.coroutines.flow.flow()
The first parameter of the flow()
is the function literal with receiver. The receiver is the implementation of FlowCollector<T>
interface, which you can call FlowCollector<T>.emit()
to emit the T
value.
2. Emit T
Value Using FlowCollector<T>.emit()
In this code example, the T
is an Int
. This flow emits Int
value from 0 → 10,000 with a 1-second interval delay.
class FlowViewModel: ViewModel()
{
val flow: Flow<Int> = flow {
repeat(10000) { value ->
delay(1000)
emit(value)
}
}
}
The
delay(1000)
simulates the process of getting the value that you want to emit (from a network call for example)
Once we have the flow, you can now collect the flow. There are different ways of collecting flow:
Flow.collectAsState()
Flow.collect()
Collect Flow — Flow.collectAsState()
collectAsState()
uses the poducestate()
compose side effect to collect the flow and automatically convert the collected value to State<T>
…