Different Ways of Building Flows
Explore different approaches to building Kotlin flows, including flowOf, emptyFlow, converting collections and functions, and using flow builders. Understand how to start and manage flow data streams for effective asynchronous programming in Android development.
We'll cover the following...
Each flow needs to start somewhere. There are many ways to do this, depending on what we need. In this chapter, we’ll focus on the essential options.
Flow raw values
The simplest way to create a flow is by using the flowOf function, where we define what values this flow should have (similar to the listOf function for a list).
package kotlinx.coroutines.app
import kotlinx.coroutines.flow.*
suspend fun main() {
flowOf(1, 2, 3, 4, 5)
.collect { print(it) }
}At times, we might also need a flow with no values. For this, we have the emptyFlow() function (similar to the emptyList function for a list).
package kotlinx.coroutines.app
import kotlinx.coroutines.flow.*
suspend fun main() {
emptyFlow<Int>()
.collect { print(it) } // (nothing)
}Converters
We can also convert every Iterable, Iterator, or Sequence into a Flow ...