Description
Describe the bug
Since #1937 Flow.cancellable()
and Flow.collect()
(just like the rest of Channels, Job, etc.) use prompt cancellation guarantee as the gold standard for cancellation.
However, the documentation for Flow.cancellable()
(https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/cancellable.html) still mentions:
Returns a flow which checks cancellation status on each emission
Flow.collect()
(https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/collect.html) doesn't even mention cancellation and the Flow
main page (https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/) only mentions using AbstractFlow
prevents common errors related to cancellation.
This all seem to imply that a collector's coroutine wouldn't be cancelled until the next emission of a flow and does not really match prompt cancellation guarantee (as far as I understand it.
Should the documentation be updated?
As it currently reads, this implies potential memory leak issues. For example:
A flow that emits somewhat infrequently with a collector that references big objects (e.g., some UI objects). The call to collect is stored in a val collector = launch { flow.collect { doStuffWithTheUI() } }
. When the collector's cancelled, the coroutine and the big UI it references remain alive until the flow
emit a new value (which could be a long time afterward).
Am I simply understanding the documentation wrong or should this be made more explicit?
Even though cancellation is cooperative and a coroutine could choose to run for a long time after being cancelled, "prompt cancellation guarantee" implies the coroutine's closure should return/be made available to the GC for collection "promptly" once cancellation is received.
(Apologies if this is the wrong avenue).
Provide a Reproducer
No reproduction steps as this is a documentation issue.