Call Kotlin suspend function in Java class

mrtaikandi :

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.

Roman Elizarov :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35725&siteId=1