IntermediateFlow

Kotlin Flow

Emit and collect a stream of values.

Dependency required: implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun numbersFlow() = flow {
    emit(1)
    emit(2)
    emit(3)
}

fun main() = runBlocking {
    numbersFlow().collect { value ->
        println(value)
    }
}
Output
1 2 3

Explanation

flow { } creates a cold flow. emit() sends values. collect {} receives each value as it arrives.

Related Tutorials