Skip to content

Instantly share code, notes, and snippets.

@vprabhu
Created August 13, 2024 06:48
Show Gist options
  • Save vprabhu/cf5f6407516f0bc97d764c7a9961e3cd to your computer and use it in GitHub Desktop.
Save vprabhu/cf5f6407516f0bc97d764c7a9961e3cd to your computer and use it in GitHub Desktop.
Simple Kotlin flow builder class that shows the implementations of flowOf() , asFlow() and flow{..}
suspend fun main() {
/**
* flowOf() -> Create a flow from fixed set of values
*/
val singleValueFlow = flowOf<Int>(578943).collect { value ->
println("Emitted Value : $value") // output : 578943
}
/*
* flowOf() -> creating a flow with multiple data types
*/
val multiValueFlows = flowOf<Any>(23, 2.90, false, "Android 1.0", 09.2008)
multiValueFlows.collect { value ->
println("multiValueFlows -> Emitted Value : $value")
//output :
//multiValueFlows -> Emitted Value : 23
//multiValueFlows -> Emitted Value : 2.9
//multiValueFlows -> Emitted Value : false
//multiValueFlows -> Emitted Value : Android 1.0
//multiValueFlows -> Emitted Value : 9.2008
}
/**
* asFlow() -> extension function on various types to convert them into Flows
*/
listOf("A", "B", "C", 4, true, 90.89).asFlow().collect { value ->
println("AsFlow Emitted Value : $value")
//output :
//AsFlow Emitted Value : A
//AsFlow Emitted Value : B
//AsFlow Emitted Value : C
//AsFlow Emitted Value : 4
//AsFlow Emitted Value : true
//AsFlow Emitted Value : 90.89
}
/**
* flow {..} -> creates a flow from the suspendable block given
*/
flow {
kotlinx.coroutines.delay(2000)
emit(890)
emit(returnSomething())
}.collect { value ->
println("flow {} Emitted Value : $value")
// output :
// flow {} Emitted Value : 890
// flow {} Emitted Value : 340
}
}
fun returnSomething(): Int {
return 340
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment