wrover
03/27/2019, 9:07 AMoleksandr
03/27/2019, 9:53 AMprivate fun launchWhenDeferredResolves(block: suspend () -> Unit) {
launch {
try {
someDeferred.await()
} catch (t: Throwable) {
if (t !is CancellationException) {
closeConnection() // <= smth like this?
}
return@launch
}
block(someDeferred)
}
}
oleksandr
03/27/2019, 9:57 AMfinally
https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/cancellation-and-timeouts.md#closing-resources-with-finallywrover
03/27/2019, 10:48 AMfun 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))
}