Last active
July 23, 2020 02:38
-
-
Save gildor/e8ef6e1cd1e085ae413ee96b8176883e to your computer and use it in GitHub Desktop.
Proof of concept for Kotlin JS coroutines delay()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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! :)