Summary - Advanced Flow
- Kotlin course
- Advanced
- Lesson 12/83
- 5 min
Combine StateFlow, SharedFlow and Channel to write an event system.
Summary - Advanced Flow
This group covered StateFlow, SharedFlow, Channel, debounce, conflate and flatMapLatest. They bring Reactive Streams style data flow to Kotlin.
StateFlow holds state, SharedFlow broadcasts events, Channel is a queue between coroutines. debounce and conflate collapse a flow; flatMapLatest manages inner flows by the latest value. Together they form a reactive surface.
Practice Summary flow with a Channel
Define val channel = Channel<Int>(). In a launch, call channel.send(10) and channel.send(20), then channel.close(). In the main flow, loop for (value in channel) and print each value with println("Got: $value").
Starter code
// Summary: Channel use
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
val channel = Channel<Int>()
launch {
channel.send(10)
channel.send(20)
channel.close()
}
for (value in channel) {
println("Got: $value")
}
}Expected output
Got: 10 Got: 20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match all Flow concepts
| Term | Meaning |
|---|---|
StateFlow |
Holds state |
SharedFlow |
Broadcasts events |
Channel |
Acts as queue |
debounce |
Time based collapse |
flatMapLatest |
Latest inner flow |
2 Which is suited for holding state?
- SharedFlow
- debounce
- Channel
- StateFlow Correct answer
Explanation: StateFlow is designed to hold state.