<@U2E974ELT> Would you be interested in this contr...
# coroutines
s
@elizarov Would you be interested in this contribution?
Copy code
public suspend inline fun <T : Closeable?, R> T.useCancellably(
        crossinline block: (T) -> R
): R = suspendCancellableCoroutine { cont ->
    cont.invokeOnCancellation { this?.close() }
    use(block)
}
e
What is the use-case?
s
For any blocking java work
e
What kind of blocking java work? Example?
s
Example:
Copy code
runBlocking {
        val foo = launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            ServerSocket(PORT).useCancellably {
                it.accept()
                // ...
            }
        }

        delay(100)

        print("Cancelling")
        foo.cancel()
    }
Or anything with
Scanner
e
Why would use blocking scokets with coroutines?
What’s wrong with a regular
use
inside a coroutine? I don’t see why you need a special function.
s
TBH, that was just a playground
But the issue is that without that function, calling
cancel
doesn't do anything
With
useCancellably
, it throws an exception and aborts the connection attempt
That's also relevant for raw
URL
streams
And any other Java stream
Current cancellability is confusing because nothing happens since the blocking work just keeps blocking indefinitely
isActive
is only useful for computational work
e
I see the point. The only problem is that is it a very dangerous thing to give to users in a lib. Many blocking closeable things in Java cannot be concurrently closed (example: JDBC connections) and by trying to close them concurrently you’ll just make it worse
👍 1
I’ll leave it to people who know what they are actually doing and they can write this function for themselves
s
Do you think it would be worth showing in the docs?
With associated caveats
e
I don’t know. Our docs are already too large. They need more simpler examples and explanations for basic concepts.
👍 1
s
Yeah, that's true 😆 😭
I think I'll just write a short Medium post or something
👍 4