Can I use Kotlin Coroutines using them in Java code?

What is my purpose?

My goal is to use the Kotlin Coroutine system with Java. I want to be able to pause the average execution for a certain amount of time, and then select a backup in this place after a specified period of time. From Java, I would like to be able to perform tasks that allow you to pause execution in the middle without asynchronous mode, for example:

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

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

What is my problem?

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

What is my question?

Kotlin Java? , ? , , Kotlin 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 */
            }
        }
    }

}

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. ^^^

+6
2

Kotlin coroutines , , , kotlinc.

, , Java Kotlin coroutines mechanic, .

+7

Thread.sleep() . , ( ), Quasar.

0

Source: https://habr.com/ru/post/1666078/


All Articles