Skip to content

Instantly share code, notes, and snippets.

@vprabhu
Created August 15, 2024 17:10
Show Gist options
  • Save vprabhu/20bf26e73451ae9ea0876e3780537d4a to your computer and use it in GitHub Desktop.
Save vprabhu/20bf26e73451ae9ea0876e3780537d4a to your computer and use it in GitHub Desktop.
This Gist describes the Kotlin flow terminal operators .
fun main() {
val flow = flow {
delay(200)
emit(1)
delay(200)
emit(2)
delay(200)
emit(2)
}
val singleFlow = flow {
emit("Single Emitted value")
}
runBlocking {
flow.collect { receivedValue ->
println("Collect Received value 1: $receivedValue")
/** Output :
* Collect Received value 1: 1
* Collect Received value 1: 2
* Collect Received value 1: 2
*/
}
val itemFirst = flow.first()
println("first() flow : $itemFirst")
/** Output :
* first() flow : 1
*/
val itemLast = flow.last()
println("last() flow : $itemLast")
/**
* last() flow : 2
*/
val itemSingle = singleFlow.single()
println("single() flow : $itemSingle") // output : single() flow : Single Emitted value
/**
* Exception in thread "main" java.lang.IllegalArgumentException: Flow has more than one element
* at kotlinx.coroutines.flow.FlowKt__ReduceKt$single$2.emit(Reduce.kt:54)
* at kotlinx.coroutines.flow.internal.SafeCollectorKt$emitFun$1.invoke(SafeCollector.kt:11)
* at kotlinx.coroutines.flow.internal.SafeCollectorKt$emitFun$1.invoke(SafeCollector.kt:11)
* at kotlinx.coroutines.flow.internal.SafeCollector.emit(SafeCollector.kt:113)
* at kotlinx.coroutines.flow.internal.SafeCollector.emit(SafeCollector.kt:82)
*/
val setFLow = flow.toSet()
println("toSet() flow : $setFLow")
/**
* Output : toSet() flow : [1, 2]
*/
val listFLow = flow.toList()
println("toList() flow : $listFLow")
/**
* toList() flow : [1, 2, 2]
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment