Skip to content

Instantly share code, notes, and snippets.

@gildor
Last active July 23, 2020 02:38
Show Gist options
  • Save gildor/e8ef6e1cd1e085ae413ee96b8176883e to your computer and use it in GitHub Desktop.
Save gildor/e8ef6e1cd1e085ae413ee96b8176883e to your computer and use it in GitHub Desktop.
Proof of concept for Kotlin JS coroutines delay()
import kotlin.coroutines.experimental.*
import kotlin.js.Date
fun main(args: Array<String>) {
println("before launch")
launch {
println("hello: ${Date()}")
delay(3000)
println("bye: ${Date()}")
}
println("after launch")
}
fun launch(block: suspend () -> Unit) {
block.startCoroutine(object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resume(value: Unit) = Unit
override fun resumeWithException(exception: Throwable) = console.error(exception)
})
}
suspend fun delay(ms: Long): Unit = suspendCoroutine { continuation ->
setTimeout({
println("timeout")
continuation.resume(Unit)
}, ms)
}
//Use top level setTimeout function instead of window.setTimeout to use with node.js
external fun setTimeout(function: () -> Unit, delay: Long)
//Output example:
//before launch
//hello: Mon Nov 20 2017 16:50:02 GMT+0800 (+08)
//after launch
//timeout
//bye: Mon Nov 20 2017 16:50:05 GMT+0800 (+08)
@pmiklos
Copy link

pmiklos commented Jul 23, 2020

wow, I completely missed that launch is included in kotlinx-coroutines-core-js. The autocomplete wasn't offering it for me so I thought it wasn't implemented or something, but now I realize it's only available inside a CoroutineScope... well, thanks again! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment