Is it possible to use coroutine code from Java?
# coroutines
p
Is it possible to use coroutine code from Java?
j
I guess you could try calling functions like runBlocking to create yourself a co-routine scope and call things synchronously. The tricky bit is calling extension functions from Java. You may want to create some Java friendly wrappers in a companion object with
JvmStatic
annotations. Should be doable on paper but not sure whether you'd want to. But doing some kind of
launch
and wrapping the returned job with a Java
Future
sounds like it might work.
Do let us know, ... kind of curious now 😉
p
Thanks, I will look into it. It looks like I can't call any functions that have the suspend modifier from Java. As long as I can get rid of them it should work...
As to why I am trying to do this: I am developing a library that is based on Kotlin coroutines. Unfortunately some clients want to use this code on the JVM using Java, which means I have to support this use-case.
d
Don't use
Future
, it's a terrible type and basically unusable. Check out kotlinx-coroutines-jdk8, which lets you convert between coroutine types such as
Deferred
and Java's
CompletableFuture
. Then you can provide a secondary API based on
CompletableFuture
for the Java consumers.
There are also interop libraries for various reactive-streams Java libraries, which you might want to consider if you have more complex use-cases: https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/README.md
p
Thank you!
a
Using kotlinx-coroutines-jdk8 to call a suspend function from Java and expose the result as CompletableFuture is quite simple, just looks odd. https://github.com/araqnid/library-versions/blob/master/java/src/main/java/org/araqnid/libraryversions/java/JavaMain.java#L85
a
This is what the google team does. 1. Create a callback based api (for java and kotlin) 2. Create some suspending extensions (like await) in place of callbacks (for kotlin-users) You endup having an api that looks good for both, kotlin and java users
m
I have used this approach
Copy code
BuildersKt.launch(GlobalScope.INSTANCE,
                Dispatchers.getMain(),
                CoroutineStart.DEFAULT,
                (coroutineScope, continuation) -> suspendFunction(arguments)
        );
which I originally found here https://stackoverflow.com/questions/52869672/call-kotlin-suspend-function-in-java-class however on a long term basis it was easier to convert the calling class to kotlin