在 Java 类中调用 Kotlin 挂起函数

新手上路,请多包涵

假设我们有以下暂停功能:

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

如果我想在我现有的一个 Java 类中调用此函数(我现在无法将其转换为 Kotlin)并获取其返回值,我必须提供一个 Continuation<? super List<MyClass>> 作为其参数(显然).

我的问题是,我怎样才能实施一个。特别是它的 getContext 吸气剂。

原文由 mrtaikandi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

首先,将 org.jetbrains.kotlinx:kotlinx-coroutines-jdk8 模块添加到您的依赖项中。在您的 Kotlin 文件中定义以下异步函数,该函数对应于编写异步 API 的 Java 风格:

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

现在使用 doSomethingAsync 来自 Java 的方式与您在 Java 世界中使用其他异步 API 的方式相同。

原文由 Roman Elizarov 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你不想使用 org.jetbrains.kotlinx:kotlinx-coroutines-jdk8 ,我有一个新想法。

在您的 kotlin 项目中编写以下代码。

     @JvmOverloads
    fun <R> getContinuation(onFinished: BiConsumer<R?, Throwable?>, dispatcher: CoroutineDispatcher = Dispatchers.Default): Continuation<R> {
        return object : Continuation<R> {
            override val context: CoroutineContext
                get() = dispatcher

            override fun resumeWith(result: Result<R>) {
                onFinished.accept(result.getOrNull(), result.exceptionOrNull())
            }
        }
    }

我把它写在我的 Coroutines

然后你可以像这样调用你的挂起函数:

             Coroutines coroutines = new Coroutines();
            UserUtils.INSTANCE.login("user", "pass", coroutines.getContinuation(
                    (tokenResult, throwable) -> {
                        System.out.println("Coroutines finished");
                        System.out.println("Result: " + tokenResult);
                        System.out.println("Exception: " + throwable);
                    }
            ));

login() 函数是一个挂起函数。

suspend fun login(username: String, password: String): TokenResult

对于您的代码,您可以:

 doSomething(getContinuation((result, throwable) -> {
       //TODO
}));

此外,您可能希望在不同线程(例如主线程)中运行回调代码,只需使用 launch(Dispathers.Main) 包装 resumeWith()

原文由 Kenvix Zure 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题