KotlinFlow: Flow Builders - devrath/KotlinAlchemy GitHub Wiki
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
funflowBuilders() {
viewModelScope.launch {
// Builder: FlowOf ---> Just one valueval demo1 = flowOf(10)
// Builder: FlowOf ---> Multiple valuesval demo2 = flowOf("x","y","z")
// Builder: AsFlow ---> Collections are converted to flowval demo3 =listOf("A","B","C").asFlow()
// Builder: Emitval 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 -------------------->ABC<----------------Builder: asFlow --------------------><-----------------------------------------------------><----------------Builder: emit ---------------------->USAINDIA<----------------Builder: emit ---------------------->