Hans Ellegard
08/29/2021, 5:00 PM// You are not allowed to change this class.
class Foo : AutoCloseable {
private val outstream = PipedOutputStream()
private val instream = PipedInputStream(outstream)
override fun close() {
instream.close()
}
fun blockingCall() {
instream.read() // blocks the thread until e.g. the stream is closed
}
}
/**
* Wraps the AutoCloseable usage so that the AutoCloseable is closed when the coroutine is cancelled.
*/
suspend fun <T: AutoCloseable> closeOnCancel(block: (T) -> Unit) {
// How do I implement this function?
// I have tried using suspendCancellableCoroutine, but I think I misunderstood that function.
}
fun cancelBlockingCall() {
val foo = Foo()
runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
withTimeout(100) {
foo.closeOnCancel { it.blockingCall() }
}
println("Yay, arriving here means problem solved")
}
}
Could I get some help or pointers to documentation regarding how to implement closeOnCancel
in general?bezrukov
08/29/2021, 6:00 PMHans Ellegard
08/30/2021, 6:28 AMrunInterruptible
, to see if it works. however, if possible, i'd like to find a way to trigger that close
call too, because such a technique feels like a cleaner way to wrap the call, as it would use the blocking API the way it was meant to.Hans Ellegard
08/30/2021, 6:44 AMfun cancelBlockingCall() {
val foo = Foo()
runBlocking {
try {
withTimeout(100) {
runInterruptible(<http://Dispatchers.IO|Dispatchers.IO>) { foo.blockingCall() }
}
} catch (e: InterruptedIOException) {
// Expected, no-op.
}
println("Yay, arriving here means problem solved")
}
}
works, at least in my example code. (Let's hope it works in my real scenario too. 🤞)
Still, I'd like to drill down to see if I can set up a solution where I call the close()
method, if nothing else so as to gain some coroutine knowledge.Hans Ellegard
08/30/2021, 7:10 AMrunInterruptible
is only available from v. 1.3.6 onwards. 😞
So I'm still looking for solutions. (No, upgrading the coroutines library is not an option.)Joe
08/30/2021, 3:19 PMHans Ellegard
08/30/2021, 4:36 PM