【发布时间】:2021-12-06 22:29:45
【问题描述】:
我正在将 Kotlin 代码添加到 Java 项目中。我用suspendCancellableCoroutine创建了一个Kotlin挂起函数
suspend fun someSuspendFunction = suspendCancellableCoroutine<Boolean>{ continuation ->
someJavaObject.someSuspendFunctionContinuation = continuation
}
我需要someSuspendFunction 来恢复在someJavaObject 中完成的一些逻辑,所以我在someJavaObject 中声明了一个字段来存储延续供以后使用。
CancellableContinuation<Boolean> someSuspendFunctionContinuation;
但是,当我想恢复它时,我找不到合适的方法来调用。在 Kotlin 中,我可以简单地调用 continuation.resume(true)。我查看了resume() 的定义,发现它叫做resumeWith(Result.success(value))。所以我试着用Java写这个:
someSuspendFunctionContinuation.resumeWith(Result.Companion.success(true))
给出此错误:'success(java.lang.Boolean)' has private access in 'kotlin.Result.Companion'
所以我尝试直接构造Result
someSuspendFunctionContinuation.resumeWith(new Result(true));
这给了我:Expected 0 arguments but found 1
是否可以构造一个 Result 以在 Java 中重用协程延续?
【问题讨论】:
标签: java android kotlin kotlin-coroutines