import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun tickerFlow(): Flow<Int> = flow {
var i = 0
while (true) {
emit(i++)
delay(100)
}
}
fun main() = runBlocking {
// Take the first 5 ticks
tickerFlow().take(5).collect { println("tick: $it") }
// Transform — same operators as List + lazy/async semantics
val sumOfFiveSquares = (1..5).asFlow()
.map { it * it }
.reduce { acc, n -> acc + n }
println(sumOfFiveSquares) // 55
// Concurrent: produce + consume in parallel
launch {
tickerFlow()
.take(3)
.collect { println("worker: $it") }
}
}
Create a free account and build your private vault. Share publicly whenever you want.