问题描述
假设我们具有以下暂停功能:
Assume we have the following suspend function:
suspend fun doSomething(): List<MyClass> { ... }
如果要在我现有的Java类之一中调用此函数(暂时无法将其转换为Kotlin)并获取其返回值,则必须提供Continuation<? super 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).
我的问题是,我该如何实施.特别是它的getContext
吸气剂.
My question is, How can I implement one. Specially its getContext
getter.
推荐答案
首先,将org.jetbrains.kotlinx:kotlinx-coroutines-jdk8
模块添加到您的依赖项中.在您的Kotlin文件中,定义以下与编写异步API的Java样式相对应的异步函数:
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() }
现在,以与使用Java世界中其他异步API相同的方式使用Java中的doSomethingAsync
.
Now use doSomethingAsync
from Java in the same way as you are using other asynchronous APIs in the Java world.
这篇关于在Java类中调用Kotlin暂停函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!