Unity (C #) & # 8594; Kotlin <- Coroutines

This is my first time experimenting with Kotlin and will be happy to help.

What the following code does is pause the execution of the current function without a sleeping executable thread. A pause is based on the amount of time provided. The function works using Coroutine support in C #. (This support was recently added to Kotlin!)

Unity example

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);
}

I could not figure out how to do something like this in Kotlin. Can someone help me in the right direction? If I find out before the response is sent, I will update my post.

Thanks in advance!

+4
source share
2

, Kotlin 1.1, EAP ( ). , API , , . , , , Kotlin 1.1.


private val executor = Executors.newSingleThreadScheduledExecutor {
    Thread(it, "sleep-thread").apply { isDaemon = true }
}

suspend fun sleep(millis: Long): Unit = suspendCoroutine { c ->
    executor.schedule({ c.resume(Unit) }, millis, TimeUnit.MILLISECONDS)
}

, . .NET, - - ( , , ), , / , , . sleep , , , sleep, . .

Kotlin coroutines, #coroutines kotlinlang. . .

+6

# Unity Kotlin kotlix.coroutines:

fun main(args: Array<String>) {
    println("Starting " + Instant.now())
    launch(CommonPool) { waitAndPrint(2.0f) }
    println("Before waitAndPrint Finishes " + Instant.now())
    // Kotlin coroutines are like daemon threads, so we have to keep the main thread around
    Thread.sleep(3000)
}

suspend fun waitAndPrint(waitTime: Float) {
    delay((waitTime * 1000).toLong()) // convert it to integer number of milliseconds
    println("waitAndPrint " + Instant.now())
}

kotlinx.coroutines , , , Kotlin .

+2

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


All Articles