我的目标是什么?
我的目标是能够使用Java中的Kotlin的Coroutine系统.我希望能够在给定的时间内暂停执行中期,然后在给定的时间过后在该位置进行备份.从Java开始,我希望能够执行允许暂停执行中的任务,而不是以异步方式执行,例如:
//example 1
someLogic();
pause(3000L); //3 seconds
someMoreLogic();
//example 2
while(true) {
someContinuedLogic();
pause(10000L); //10 seconds
}
Run Code Online (Sandbox Code Playgroud)
我的问题是什么?
正如预期的那样,我能够完全从Kotlin执行协同程序,但是当谈到Java时,它变得棘手,因为代码的Java部分立即执行整个块而没有任何暂停,而Kotlin块正确地暂停1,并且然后4秒.
我的问题是什么?
甚至可以使用Kotlin作为Java协程的主干吗?如果是这样,我做错了什么?下面你可以找到源代码,展示我如何尝试在Java中使用Kotlin的协同程序.
KtScript类
abstract class KtScript {
abstract fun execute()
fun <T> async(block: suspend () -> T): CompletableFuture<T> {
val future = CompletableFuture<T>()
block.startCoroutine(completion = object : Continuation<T> {
override fun resume(value: T) {
future.complete(value)
}
override fun resumeWithException(exception: Throwable) {
future.completeExceptionally(exception)
}
})
return future
}
suspend fun <T> await(f: CompletableFuture<T>): T =
suspendCoroutine { c: Continuation<T> -> …
Run Code Online (Sandbox Code Playgroud) 我是第一次尝试Kotlin并希望得到一些帮助.
下面的代码是暂停执行当前函数而不休眠执行线程.暂停基于提供的时间量.该函数使用C#语言中的Coroutine支持.(这个支持最近也加入了Kotlin!)
Unity示例
void Start()
{
print("Starting " + Time.time);
StartCoroutine(WaitAndPrint(2.0F));
print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime)
{
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何在Kotlin做类似的事情.有人可以帮我指导正确的方向吗?如果我在发布答案之前弄明白,我会更新我的帖子.
提前致谢!