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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With