https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

v0ldem0rt

12/06/2020, 3:02 AM
I am trying to write a suspend function that can listen to cancellation of continuation, and invoke a suspended callback. Here is what I am looking at:
Copy code
suspend fun <T> PreparedStatement.withCancellation(callback: suspend () -> T): T {
    val stmt = this
    suspendCancellableCoroutine { cont ->
        cont.invokeOnCancellation { 
            stmt.cancel()
        }
    }

    return callback()
}
z

Zach Klippenstein (he/him) [MOD]

12/06/2020, 11:37 AM
Copy code
try {
  awaitCancellation() 
} finally {
  this.cancel()
  callback()
}
3 Views