-
Notifications
You must be signed in to change notification settings - Fork 1.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve API for cooperative cancellation in Flow #2026
Comments
* flow builder is cancellable by default * New unambiguous currentContext top-level function * New Flow.cancellable() operator * Set of lint to catch programmer's errors in compile time Fixes #2026
* flow builder is cancellable by default * New unambiguous currentContext top-level function * New Flow.cancellable() operator * Set of lint to catch programmer's errors in compile time Fixes #2026
The scope of this issue is clear, but isn't not clear the difference between What "current" stand for? |
@fvasco Consider the following example:
But
|
Hi @elizarov, thank you for response. I suggest you to reread your reply, I consider it a little tricky, it is not really easy to understand for a newbie. |
@fvasco It is tricky, indeed, because you can accidentally capture the (wrong) outer context. There's not much we can do, but to warn on potentially invalid code. That's what we do, too. As for naming, it is not clear how |
Thank you, @elizarov, Maybe the best solution is to provide |
Thanks, indeed. Corrected. |
The latest part of Kotlin#2026
Make Flow more cancellation friendly: * flow builder is cancellable by default * New unambiguous currentCoroutineContext top-level function * New Flow.cancellable() operator Fixes Kotlin#2026
The latest part of Kotlin#2026
Problem statement
Currently, Flow cancellation is hard to get right. For example, the following code:
will print 100 lines with no easy way to prevent this behaviour in a more generic case.
One may decide to rewrite the source in the following manner:
but this is incorrect because
isActive
can only be captured from an enclosing CoroutineScope (whether it is otherrunBlocking
orMyActivity : CoroutineScope
).Making each
emit
call cancellation friendly is impractical for performance reasons, e.g. when no cancellation and/or thread-safety is involved.Proposal
flow {}
builderemit
methods cancellable. This builder already performs various checks to preserve both exception and context transparency, so adding one more is negligiblecancellable()
operator for the flows that are not cancellable by defaultcurrentCoroutineContext()
method that retrieveskotlin.coroutines.coroutinesContext
and does not clash withCoroutineScope
memberThe text was updated successfully, but these errors were encountered: