Simple question before I dug into it, does corouti...
# coroutines
a
Simple question before I dug into it, does coroutines works on Kotlin/JS ?
j
Yes, coroutines are multiplatform
a
Thanks !
Does it uses a worker then ?
j
No
Workers are heavyweight and have their own heap (kinda, there's some sharing)
a
How does it works so ?
j
It uses setTimeout
j
The default dispatcher on JS uses
window.postMessage
in browsers with a window, and
process.nextTick
on NodeJS. Or it falls back to
setTimeout
if neither
window
nor
process
is available in the environment: https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/js/src/CoroutineContext.kt#L15 Having coroutines doesn't mean having true parallelism. Coroutines are a framework for dealing with concurrency, just like promises and
setTimeout
do. You don't need actual multithreading to run coroutines, they can interleave on a single thread for instance.
a
Oh okay thanks I see, because I'm making a Minecraft-like game in 2D in the browser, but I want the world generation of blocks to be non-blocking as for now it freezes the entire window
l
Use yield() during the steps of the world generation process to allow other code to run
e
if you do need real parallelism (maybe it's too computationally heavy even with yielding) you will need to build on
Worker
, there isn't much support for it in Kotlin but it's just `postMessage`'ing between independent scripts. (https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.workers/ is wrappers for service workers which are quite a bit more complex than web workers)
a
I'll try using workers then, thanks for the information !