Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity (C#) -> Kotlin <- Coroutines

I'm experimenting with Kotlin for the first time and would like to use Coroutine.

What the code below does is pause the execution of the current function without sleeping the executing thread. The pause is based on the amount of time provided. The function works by using the Coroutine support in the C# language. (This support was also 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 haven't been able to figure out how to do something similar in Kotlin. Can someone help guide me in the right direction?

like image 281
Wonderlus Avatar asked Dec 23 '22 21:12

Wonderlus


1 Answers

Keep in mind that coroutines are part of Kotlin 1.1 which is still in EAP (early access preview). While I personally have experienced great success, the API is not stable yet and you should not rely on it working in production. Also, this answer is likely to become out of date by the time Kotlin 1.1 is finalized.

  1. If you haven't already, upgrade your project and your IDE to the latest Kotlin 1.1 EAP milestone (M04 at the time of this writing) by following the instructions at the bottom of this blog post.
  2. Find or write a function that will do what you want.
    • kotlinx.coroutines has quite a few, though not the one you're looking for in this case.
    • Fortunately it turns out to be quite easy to write a non-blocking sleep:


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

There are some important caveats to be aware of. Compared to .NET where all suspendable methods will be worked on by some shared central pool somewhere (I'm not even sure where, to be honest), the example sleep method linked/shown above will run all continued work in the executor pool that you specify. The example sleep method linked above uses a single thread, which means all work that occurs after sleep will be handled by a single thread. That may not be sufficient for your use case.

If you have additional questions about the details of Kotlin's coroutines, I highly recommend joining the #coroutines channel in the kotlinlang slack. See here for details on joining.

like image 50
ean5533 Avatar answered Dec 28 '22 08:12

ean5533