I'm completely at a loss here as to how to use `Co...
# announcements
l
I'm completely at a loss here as to how to use
Continuation
in my Java code when trying to run async coroutines. Anyone have any resources?
d
As far as I know you shouldn't. Use the higher-level "glue code" from the coroutines integration libraries: https://github.com/Kotlin/kotlinx.coroutines/blob/master/integration/README.md That allows you to convert from coroutines to e.g.
CompletableFuture
or
ListenableFuture
.
l
Thank you.
d
(and vice versa allows you to
await
on a
CompletableFuture
, etc.)
l
I'm needing to target API 19 in Android, so that's a no go for me.
Thank you anyway.
d
Well, you can (in theory) use
Continuation
from Java by calling
resumeWith
on it, but that could be problematic because that requires an inline-class parameter. You'd have to write a helper method in Kotlin:
fun <T> resumeContinuation(continuation: Continuation<T>, value: T) = continuation.resume(value)
And then call that from Java.
And same for
resumeWithException
l
Thank you. So this seems to be working OK, but does the Continuation instance have to be so verbose?
Copy code
Object addresses = geo.reverseGeocodeAsync(location.getLatitude(), location.getLongitude(), 5).await(new Continuation<List<Address>>() {
            @NotNull
            @Override
            public CoroutineContext getContext() {
                return GlobalScope.INSTANCE.getCoroutineContext();
            }

            @Override
            public void resumeWith(@NotNull Object o) {

            }
        });
And should anything be done in
resumeWith
?
d
honestly you should not be implementing continuation manually. Instead provide a java-adapted version from kotlin.
Copy code
fun myFunctionAsync(): Deferred<Result> {

}

fun myFunctionForJava(callback: Consumer<Result>) {
    // adapt deferred to callback here
}
However this is not a trivial task, as you need to properly handle cancellation, exceptions, etc. I highly urge you to check out https://github.com/Kotlin/kotlinx.coroutines/blob/master/integration/kotlinx-coroutines-guava/src/ListenableFuture.kt to see how not-easy this is.
l
Thank you. What a nightmare. Been at it for hours.
d
If at all possible, consider using Guava and
ListenableFuture
. Or just write all your async code in Kotlin K
l
Yeah, I tried that initially but when calling suspend functions from Java, the return type is
Object
d
Yes, you cannot reasonably call
suspend
functions from Java. You need adapters (written in Kotlin) that translate to something Java can handle (like
ListenableFuture
)
l
Cool, thank you.
g
you can always wrap suspended code in a kotlin class and pass the scope and a good ol' callback there
­čĹŹ 1