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()
flow()
functionIt 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.
fun flow_builder(): Flow<String> = flow { emit ("A") emit ("B") emit ("C") } suspend fun main() { flow_builder() .collect { println(it) } }
flowof()
functionThe flowof()
function is the easiest way to build a flow. We use it to define a flow with a fixed amount of values.
asFlow()
functionIt is used to convert a sequence or a range into a flow.
emptyFlow()
functionAs the name hints, it is used when we want to create an empty flow.
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) } }
flowof()
function for building a flow.collect
method to print all the values the flow consists of.asFlow()
function to convert a range or sequence into a flow.emptyFlow()
function to create a flow with no value.Free Resources