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

james

01/19/2021, 2:28 PM
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

louiscad

01/19/2021, 3:06 PM
There's already built-in integration modules in kotlinx.coroutines for these.
j

james

01/19/2021, 4:18 PM
@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

louiscad

01/19/2021, 5:20 PM
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

james

01/19/2021, 6:03 PM
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

louiscad

01/19/2021, 6:05 PM
It's not so bad I think.
y

Yigitunlu

01/20/2021, 7:46 AM
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. 😅
14 Views