【发布时间】:2019-05-30 01:55:05
【问题描述】:
我正在尝试从 Java 7 调用 Kotlin 函数。我正在使用协程,这个被调用的函数正在挂起,例如:
suspend fun suspendingFunction(): Boolean {
return async { longRunningFunction() }.await()
}
suspend fun longRunningFunction() : Boolean {
delay(400)
return true
}
我在 0.25.3 版本中使用协程,我可以通过将 Continuation<U> 实例作为参数传递给挂起函数来模拟简单的 Java 回调样式,例如
CoroutinesKt.suspendingFunction(new Continuation<Boolean>() {
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resume(Boolean value) {
doSomethingWithResult(value);
}
@Override
public void resumeWithException(@NotNull Throwable throwable) {
handleException(throwable);
}
});
但是,在更新到完全稳定的 1.0.1 版本后,我认为它不再可能了。假设暂停功能的更新版本如下所示:
suspend fun suspendingFunction(): Boolean {
return GlobalScope.async { longRunningFunction() }.await()
}
Continuation<U> 现在使用 Result 类,这在 Java 中似乎无法使用(这是有道理的,因为它是内联类)。我试图使用协程中Continuation 的一些子类,但它们都是内部的或私有的。
我知道它通常是 advised to transform coroutine to CompletableFuture,但我使用的是 Android,这意味着只有 Java 7。另一方面,简单的Future 太笨了,因为我不想定期检查函数是否完成——我只想在它完成时被调用。而且我真的很想避免添加新库或许多其他类/方法。
有没有什么简单的方法可以直接从 Java 7 调用挂起函数?
由于 Kotlin 试图与 Java 进行非常好的互操作,我想会有一些简单的方法来做到这一点,但我还没有找到。
【问题讨论】:
标签: java android kotlin coroutine kotlinx.coroutines