What are different types of flow builders in Kotlin coroutines?
What is a flow builder?
Flow can provide multiple values and is built on top of the coroutines. Flow is a stream of data that is computed asynchronously. The data should be of the same type; if the flow is of type int, the values emitted by the flow should only be an integer.
Each flow needs to begin somewhere. A flow builder is an interface we use to build a flow. There are different ways in which we can build a flow. Let’s discuss them one by one:
flowOf()asFlow()emptyFlow()flow()
The flow() function
It is the most popular way to build a flow. We start this builder with a flow function call, and inside that builder, we emit the values of the flow.
Example
fun flow_builder(): Flow<String> = flow {
emit ("A")
emit ("B")
emit ("C")
}
suspend fun main() {
flow_builder()
.collect { println(it) }
}Explanation
- Line 1: Create a function using flow builder of type String; that will print values of type string.
- Line 2-4: Use emit method to emit the values from the flow.
The flowof() function
The flowof() function is the easiest way to build a flow. We use it to define a flow with a fixed amount of values.
The asFlow() function
It is used to convert a sequence or a range into a flow.
The emptyFlow() function
As the name hints, it is used when we want to create an empty flow.
Example
suspend fun main() {
print("flowof() : ")
flowOf(1, 3, 9, 16)
.collect { print("${it} ") }
println("")
print("asFlow() : ")
(1..10).asFlow()
.collect { print("${it} ")}
println("")
print("emptyFlow() : ")
emptyFlow<Int>()
.collect { print(it) }
}Explanation
- Line 1: Create a main suspending function.
- Line 3: Use the
flowof()function for building a flow. - Lines 4, 9, and 14: Use the
collectmethod to print all the values the flow consists of. - Line 8: Use the
asFlow()function to convert a range or sequence into a flow. - Line 13: Use the
emptyFlow()function to create a flow with no value.
Free Resources