Call Kotlin suspend function in Java class

2019-03-28 12:31发布

问题:

Assume we have the following suspend function:

suspend fun doSomething(): List<MyClass> { ... }

If I want to call this function in one of my existing Java classes (which I'm not able to convert to Kotlin for now) and get its return value I have to provide a Continuation<? super List<MyClass>> as its parameter (Obviously).

My question is, How can I implement one. Specially its getContext getter.

回答1:

First, add org.jetbrains.kotlinx:kotlinx-coroutines-jdk8 module to your dependencies. In your Kotlin file define the following async function that corresponds to Java style of writing async APIs:

fun doSomethingAsync(): CompletableFuture<List<MyClass>> =
    GlobalScope.future { doSomething() }

Now use doSomethingAsync from Java in the same way as you are using other asynchronous APIs in the Java world.