我可以在Java代码中使用它们来利用Kotlin的Coroutines吗? [英] Can I take advantage of Kotlin's Coroutines by using them in Java code?

查看:102
本文介绍了我可以在Java代码中使用它们来利用Kotlin的Coroutines吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是什么?

我的目标是能够使用Java中的Kotlin Coroutine系统。我希望能够在给定的时间内暂停执行中期,然后在给定的时间过后在该位置选择备份。从Java开始,我希望能够执行允许暂停执行中的任务,而不是以异步方式执行,例如:

My goal is to be able to use Kotlin's Coroutine system from Java. I want to be able to pause mid-execution for a given amount of time, and then pick back up at that spot after the given amount of time has passed. From Java, I'd like to be able to execute tasks that allow pausing mid-execution without in an asynchronous fashion, such as:

//example 1
someLogic();
pause(3000L); //3 seconds
someMoreLogic();

//example 2
while(true) {
    someContinuedLogic();
    pause(10000L); //10 seconds
}

我的问题是什么?

正如预期的那样,我能够完全从Kotlin执行协同程序,但是当谈到Java时,它变得棘手,因为代码的Java部分执行整个块一次没有任何停顿,而Kotlin区块正确暂停1,然后是4秒。

As expected, I am able to execute coroutines perfectly fine from Kotlin, but when it comes to Java, it becomes tricky because the Java part of the code executes the entire block at once without any pauses, whereas the Kotlin block correctly pauses 1, and then 4 seconds.

我的问题是什么?

甚至可以使用Kotlin作为Java协程的主干吗?如果是这样,我做错了什么? 下面你可以找到源代码,展示我如何尝试在Java中使用Kotlin的协同程序。

Is it even possible to use Kotlin as a backbone for coroutines in Java? If so, what am I doing wrong? Below you can find the source code showing how I am attempting to use Kotlin's coroutines in Java.

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> ->
                f.whenComplete { result, exception ->
                    if (exception == null)
                        c.resume(result)
                    else
                        c.resumeWithException(exception)
                }
            }

    fun pause(ms: Long): CompletableFuture<*> {
        //todo - a better pausing system (this is just temporary!)
        return CompletableFuture.runAsync {
            val currentMs = System.currentTimeMillis()
            while (System.currentTimeMillis() - currentMs < ms) {
                /* do nothing */
            }
        }
    }

}

Kotlin执行代码

fun main(args: Array<String>) {
    ScriptTestKotlin().execute()
}

class ScriptTestKotlin : KtScript() {
    override fun execute() {
        println("Executing Kotlin script from Kotlin...")
        val future = async {
            await(pause(1000L))
            println("   1 second passed...")
            await(pause(4000L))
            println("   5 seconds passed...")
        }
        future.get() //wait for asynchronous task to finish
        println("Finished!")
    }
}

Kotlin执行结果

Executing Kotlin script from Kotlin...
   1 second passed...
   5 seconds passed...
Finished!

Java执行代码

public class ScriptTestJava extends KtScript {

    public static void main(String[] args) {
        new ScriptTestJava().execute();
    }

    @Override
    public void execute() {
        System.out.println("Executing Kotlin script from Java...");
        CompletableFuture<?> future = async(continuation -> {
            await(pause(1000L), continuation);
            System.out.println("    1 second passed...");
            await(pause(4000L), continuation);
            System.out.println("    5 seconds passed...");
            return continuation;
        });
        try {
            future.get(); //wait for asynchronous task to finish
        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println("Finished!");
    }
}

Java执行结果

Executing Kotlin script from Java...
    1 second passed...
    5 seconds passed...
Finished!

^^^不幸的是,在Java中跳过了暂停。 ^^^

^^^ Unfortunately, the pauses are skipped in Java. ^^^

推荐答案

Kotlin协同程序是通过对代码的编译器转换实现的,显然只能通过<$ c来完成$ c> kotlinc 。

Kotlin coroutines are implemented with a compiler transformation to the code, which obviously can only be done by kotlinc.

所以,不,Java不能使用Kotlin的协同机制,因为它是一个编译时功能。

So, no, Java cannot use Kotlin's coroutines mechanic since it is a compile-time feature.

这篇关于我可以在Java代码中使用它们来利用Kotlin的Coroutines吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆