When working with Java `Future` or `CompletableFut...
# coroutines
j
When working with Java
Future
or
CompletableFuture
in JVM > 8 within
suspendCoroutine
what's the suggested pattern for interaction. From what I can tell, the
suspendCoroutine
is designed for an asynchronous callback but from what I can tell JDK 11, 12, 13 and 14 don't have a way to implement a CompletionStage interface.
For color what i'm doing now is
Copy code
fun <T> Future<T>.await(): T = this.get()
But this seems inherently incorrect and i'm looking for some suggestions on ways to improve this.
🚫 1
l
There's already built-in integration modules in kotlinx.coroutines for these.
j
@louiscad I'm assuming your referring to this: https://github.com/Kotlin/kotlinx.coroutines/blob/22087ef122b5ac677fd14941a18b6aef[…]7393d2/integration/kotlinx-coroutines-jdk8/src/future/Future.kt This is only available on CompletionStage and not
Future
l
For Future itself, that's a poor primitive, and I think the best you can do is wrap the call to
get
in
<http://Dispatchers.IO|Dispatchers.IO> { }
.
j
Launching on an IO thread doesn't continue the scope, this is more or less what I was thinking:
Copy code
suspend fun <T> Future<T>.await(): T = coroutineScope {
    // If coroutine is cancelled, cancel the future as well
    val cancelJob = launch {
        suspendCancellableCoroutine { cont ->
            cont.invokeOnCancellation {
                this@await.cancel(true)
            }
        }
    }
    while (!isDone) {
        delay(1)
    }
    cancelJob.cancel()
    this@await.get()
}
But obviously that's still sub-optimal.
l
It's not so bad I think.
y
You can wrap it with a callbackflow
I i've just tried to implement what you'd mentioned. I'm not sure this is what you wanted. 😅