Skip to content

KotlinFlow: Flow Builders

Devrath edited this page Dec 24, 2023 · 2 revisions

Basic Flow Builders in Kotlin

Flow Builder Description
flowOf Creates a flow from a fixed set of values.
asFlow Converts other types (e.g., collections) into flows.
emit Creates a flow using the flow builder and emits values using the emit function.

Code

     fun flowBuilders() {
        viewModelScope.launch {

            // Builder: FlowOf ---> Just one value
            val demo1 = flowOf(10)
            // Builder: FlowOf ---> Multiple values
            val demo2 = flowOf("x","y","z")
            // Builder: AsFlow ---> Collections are converted to flow
            val demo3 = listOf("A","B","C").asFlow()
            // Builder: Emit
            val demo4 = flow<String> {
                emit("USA")
                delay(500)
                emit("INDIA")
            }

            println("<-------- Builder: FlowOf ---> Just one value -------->")
            demo1.collect{
                println(it)
            }
            println("<-------- Builder: FlowOf ---> Just one value -------->")
            println("<----------------------------------------------------->")
            println("<-------- Builder: FlowOf ---> Multiple one value ---->")
            demo2.collect{
                println(it)
            }
            println("<-------- Builder: FlowOf ---> Multiple one value ---->")
            println("<----------------------------------------------------->")
            println("<---------------- Builder: asFlow -------------------->")
            demo3.collect{
                println(it)
            }
            println("<---------------- Builder: asFlow -------------------->")
            println("<----------------------------------------------------->")
            println("<---------------- Builder: emit ---------------------->")
            demo4.collect{
                println(it)
            }
            println("<---------------- Builder: emit ---------------------->")

        }
    }

Output

<-------- Builder: FlowOf ---> Just one value -------->
10
<-------- Builder: FlowOf ---> Just one value -------->
<----------------------------------------------------->
<-------- Builder: FlowOf ---> Multiple one value ---->
x
y
z
<-------- Builder: FlowOf ---> Multiple one value ---->
<----------------------------------------------------->
<---------------- Builder: asFlow -------------------->
A
B
C
<---------------- Builder: asFlow -------------------->
<----------------------------------------------------->
<---------------- Builder: emit ---------------------->
USA
INDIA
<---------------- Builder: emit ---------------------->
Clone this wiki locally