emit is the FlowCollector operation for offering a value to a Flow collector. It may suspend until the collector processes that value, making it an asynchronous return from a flow builder. section 16.2.1
Emitting values over time
fun createValues(): Flow<Int> = flow { emit(1) delay(1000.milliseconds) emit(2) delay(1000.milliseconds) emit(3) } runBlocking { createValues().collect { println(it) } } Each value becomes available as soon as emit is reached; collection does not wait for the entire sequence to be produced. section 16.1.1
The operation’s behavior follows the flow’s execution model:
- A flow builder creates an initially inert cold Flow; its body runs only when a terminal operation such as collect starts collection. section 16.2.1
- Inside flow, the receiver is a FlowCollector, which supplies emit; calling emit invokes the collector lambda and resumes the builder after that lambda finishes. section 16.2.4
- emit is both a suspension point and a cancellation point, so cancelling the collector coroutine stops collection when execution reaches emit or another cancellation point. section 16.2.3
Listing 16.3 Calling suspending functions from the flow builder
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.time.Duration.Companion.milliseconds
fun main() {
val letters = flow {
log("Emitting A!")
emit("A") #1
delay(200.milliseconds)
log("Emitting B!")
emit("B")
}
}
A compact listing shows emit alongside delay inside a flow builder, making suspension between emissions immediately visible. section 16.2.1
