flow {} builder operator semantics in Kotlin 1.9.0
0 reputation · 31 Jul 2020, 01:18 UTC
The flow {} builder introduced in Kotlin 1.9.0 redefines operator semantics for lazy sequential collection. This change affects how collectors are registered and retained across coroutine scope boundaries, particularly when a flow value is captured in a ViewModel or passed between suspension functions.
A precise goal is to determine whether the builder automatically terminates its collector upon scope cancellation or whether explicit closure is required to prevent retained collector references that persist after the originating coroutine exits. The relevant uncertainty centers on the interaction between the new operator flow {} and existing cancellation mechanisms in coroutineScope, and whether compiler-inferred scope lifetimes accurately track the builder's internal collector.
Does the flow {} builder close its collector when the parent coroutine scope cancels? What patterns ensure collector termination when the flow is stored in a long-lived object? Are there compiler flags or operator adaptations that reconcile the builder's semantics with explicit resource management?