liveBook · Manning

Emit

As explained in Kotlin in Action, 2E

emit is the FlowCollector operation that publishes a value to a Flow collector and may suspend or respond to cancellation.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, suspension, cancellation, cold-flow timing, and FlowCollector-to-collector calls, but defers broader flow operators.
Examples
Uses delayed letter and integer flows, an infinite counter flow, collector cancellation, and minimal Flow and FlowCollector interfaces.
What it assumes
Assumes basic Kotlin coroutines and lambdas while introducing Flow, FlowCollector, cold-flow collection, and asynchronous emission.
What you can do after
Apply emit to build cold flows that deliver values over time and respond to collector suspension or cancellation.
How it connects
Connects emit with Flow, FlowCollector, collect, cold flows, suspending functions, coroutines, and cancellation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.