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) |
@pmiklos Hah, glad it helped, this is very-very old gist, from times when there was no Kotlinx.Coroutines for JS, now I think it's better to use the official implementation from kotlinx.coroutine, the biggest gain is that it would be cancelable, for now, there is no standard way to make it cancellable without kotlinx.coroutines (at least until the keep about adding cancellation APIs to stdlib will be confirmed)
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
Thanks Andrey, I wish I had found your solution sooner, that would have saved me a couple hours of headache. I couldn't figure out how to use setTimout/setInterval with suspending functions without introducing some kind of deadlock.