Kotlin Flow timeout operator and Java ExecutorService integration: does timeout cancel upstream collector or only drop emissions?
0 reputation · 17 Mar 2023, 03:23 UTC
When a Kotlin Flow is collected on a dispatcher created with Dispatchers.from(ExecutorService), applying the timeout operator raises a design question about what happens to the upstream collector when the timeout expires. The timeout operator may either cancel the upstream collector, triggering its onCompletion and releasing resources tied to the ExecutorService, or it may simply stop emitting further values while leaving the collector active. This distinction matters because the ExecutorService may continue to run submitted tasks unless the underlying thread is interrupted or the dispatcher is shut down.
Given the differing behavior of timeout across StateFlow and channel‑based flows, and the need to ensure that Java‑backed threads do not linger after a timeout, it is unclear whether the current implementation propagates cancellation upstream or merely drops emissions.
Does the timeout operator cancel the upstream collector when used with an ExecutorService‑backed dispatcher? If not, what additional steps are required to guarantee that the ExecutorService releases its resources after a timeout?