简体   繁体   English

如何在 Java 中恢复 Kotlin 协程延续

[英]How to resume a Kotlin Coroutine Continuation in Java

I am adding Kotlin code to a Java project.我正在将 Kotlin 代码添加到 Java 项目中。 I created a Kotlin suspend function with suspendCancellableCoroutine我用suspendCancellableCoroutine创建了一个 Kotlin 挂起函数

suspend fun someSuspendFunction = suspendCancellableCoroutine<Boolean>{ continuation ->
     someJavaObject.someSuspendFunctionContinuation = continuation
}

I need someSuspendFunction to resume by some logic done in someJavaObject so I declare a field in someJavaObject to store the continuation for later use.我需要someSuspendFunction在做一些逻辑来恢复someJavaObject所以我宣布现场someJavaObject存储供以后使用的延续。

CancellableContinuation<Boolean> someSuspendFunctionContinuation;

However, when I want to resume it, I can't find a proper method to call.但是,当我想恢复它时,我找不到合适的方法来调用。 In Kotlin I can simply call continuation.resume(true) .在 Kotlin 中,我可以简单地调用continuation.resume(true) I looked into the definition of resume() and found it called resumeWith(Result.success(value)) .我查看了resume()的定义,发现它叫做resumeWith(Result.success(value)) So I tried to write this in Java:所以我试着用 Java 写这个:

someSuspendFunctionContinuation.resumeWith(Result.Companion.success(true))

which gives this error: 'success(java.lang.Boolean)' has private access in 'kotlin.Result.Companion'这给出了这个错误: 'success(java.lang.Boolean)' has private access in 'kotlin.Result.Companion'

So I tried to construct Result directly所以我尝试直接构造Result

someSuspendFunctionContinuation.resumeWith(new Result(true));

This gives me : Expected 0 arguments but found 1这给了我: Expected 0 arguments but found 1

Is it possible to construct a Result with value to reusme a coroutine continuation in Java?是否可以构造一个带值的Result来重用 Java 中的协程延续?

You can create a Result object using reflection:您可以使用反射创建一个Result对象:

public void resume() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    var successMethod = Result.Companion.getClass().getDeclaredMethod("success", Object.class);
    successMethod.setAccessible(true);

    someSuspendFunctionContinuation.resumeWith(successMethod.invoke(Result.Companion, true));
}

But I think it is better to just create yourself a very small util in Kotlin for using it in Java:但我认为最好在 Kotlin 中为自己创建一个非常小的 util 以便在 Java 中使用它:

fun <T> resumeContinuationWithSuccess(cont: Continuation<T>, value: T) {
    cont.resumeWith(Result.success(value))
}
public void resume() {
    SuspendUtils.resumeContinuationWithSuccess(someSuspendFunctionContinuation, true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM