Skip to workspace
Kotlin Lab

Kotlin on the JVM / Chapter 05

Collect a cold Flow on demand

Read enough sensor samples to fill an alert panel and release the upstream producer.

The decision

A cold sensor feed opens a connection on collection. Return the first limit readings at or above 70, in source order. Zero opens no connection. Negative limits are invalid. The same returned pipeline can be collected twice against the cold source.

Read the Kotlin

Count accepted readings at the filter output

A Flow describes values over time. filter forwards only samples passing the predicate. The following take(n) counts those forwarded samples and stops upstream collection as soon as the nth is received. Trace the inputs until the count reaches the limit. Later readings are never requested from this sequential cold producer.

flowOf(61, 70, 64, 81, 95).filter { it >= 70 }.take(2).toList()
// Receives 70 and 81 and stops before 95.

Distinguish building a flow from collecting it

The block inside flow { ... } runs when a terminal operation such as toList() collects it. Saving the pipeline in a val saves its instructions. A second collection starts a fresh run of this cold source. An external counter or a newly opened connection can therefore give different observations on the second run.

var visits = 0
val feed = flow { emit(++visits) }
feed.toList()  // [1]
feed.toList()  // [2]

Handle a zero limit when constructing the panel

Flow.take validates its argument when the operator is called and requires a positive count. The producer can still be cold while the operator rejects zero immediately, even if nobody collects. Returning emptyFlow() for a zero-sized panel represents a valid empty result and avoids opening the sensor. The outer require gives negative limits a separate, explicit failure.

The full example

Java 25
import java.util.function.Supplier;
import java.util.stream.Stream;

class Lesson {
    static Supplier<Stream<Integer>> hotReadings(
            Supplier<Stream<Integer>> samples, int limit) {
        if (limit < 0) throw new IllegalArgumentException("negative limit");
        return () -> limit == 0
            ? Stream.empty()
            : samples.get().filter(n -> n >= 70).limit(limit);
    }
}
Kotlin/JVM
import kotlinx.coroutines.flow.*

fun hotReadings(samples: Flow<Int>, limit: Int): Flow<Int> {
    require(limit >= 0)
    return if (limit == 0) emptyFlow()
           else samples.filter { it >= 70 }.take(limit)
}

Inputs and outcomes

InputOutcomeWhy it matters
68, 72, 69, 74, 80; limit 2[72, 74]Stop upstream after the second qualifying reading.
Source would open a connection; limit 0[]Do not subscribe to the source.
Collect twice; cold source emits 73 each time[73] then [73]Each collection starts the source anew.

Walk through the code

  1. The Java API returns a Supplier of fresh streams. Each get can construct a new pipeline. limit short-circuits traversal. A caller reading a resource-backed Java stream must also close it, typically with try-with-resources.
  2. filter applies the threshold before take counts alerts. At the limit, take stops this upstream collection and the producer can release its connection in finally. Collecting a cold flow built with flow { … } runs its block again with a fresh connection.
  3. Flow.take requires a positive count. An explicit emptyFlow() handles a zero-sized panel without touching the sensor. require rejects a negative count when the caller builds the pipeline.

The Java habit

Moving take(limit) before filter makes cool samples consume display slots. Eagerly converting the whole feed to a list could also wait forever when the sensor stays connected.

When to choose differently

For a live feed shared by multiple screens, opening a new sensor connection on each collection can waste resources. A shared producer such as SharedFlow changes the lifetime and replay policy, which need their own design.

References

Open quizTry code