Is there a way to write an adapter for a coroutine...
# announcements
w
Is there a way to write an adapter for a coroutine to intercept cancellation in order to encapsulate nonstandard behavior, e.g. close an underlying socket to interrupt blocking method?
o
Copy code
private fun launchWhenDeferredResolves(block: suspend () -> Unit) {
    launch {
            try {
                someDeferred.await()
            } catch (t: Throwable) {
                if (t !is CancellationException) {
                    closeConnection() // <= smth like this?
                }
                return@launch
            }
        block(someDeferred)
    }
}
w
Not exactly, I were to have ability to cancel blocking method. Something like that:
Copy code
fun main() = runBlocking {
    val job = launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        val socket = ServerSocket(23546)
        socket.useCancellably {
            it.accept()
        }
    }
    delay(1000)
    job.cancel()
}

suspend inline fun <T : Closeable?, R> T.useCancellably(crossinline block: (T) -> R): R =
    suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation { this?.close() }
        continuation.resume(use(block))
    }