Kotlin

Flow — Cold Async Streams

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`Flow<T>` is a coroutine-based reactive stream — like Sequence but async. Cold (each collector restarts the producer) and respects cancellation. The backbone of modern Kotlin/Android reactive code.
Kotlin
Raw
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") }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.