what's the advantage of coroutines over jvm thread...
# coroutines
x
what's the advantage of coroutines over jvm threads? in js do they work as workers? what happens when you compile to native?
g
To be honest threads and coroutines are different layers of abstraction. You just can program “light weight threads” on coroutines, but it’s just an abstraction on callbacks
Instead of thinking about coroutines as about threads, I would better suggest to think about them as nice syntax for callbacks, where you can use sequential-like code style with asyncronous callback-based API
Also out of the box (stdlib and language support) coroutines has nothing with threads, threading or backround tasks, just an abstraction for callbacks
in js do they work as workers
In theory it’s possible to use workers (need a way how to serialize coroutine content to run on worker), but no, coroutines on JS are single-threaded and do the same thing as coroutines in JS, allows to do things like:
val result = fetch("...").await()
So provide nice way to work with async code
what happens when you compile to native
Currently coroutines on K/N are also single threaded for now. But milti-threaded will be available at some point https://github.com/Kotlin/kotlinx.coroutines/issues/462
what’s the advantage of coroutines over jvm threads
I said that coroutines and threads are very different and it’s true. But you can solve with coroutines problems that you usually solve with threads, like what if you have some IO where most of the time you just wait for result and do nothing. You can just block thread and wait, but because threads are heavy weight (consume a lot of memory, this is sytem calls etc) you waste resources waiting. But coroutines are light weight, it’s just an object, so instead block you can suspend (wait for “callback” result) Also in some cases you just cannot block thread (like in case of UI thread), so you need somehow move job to background you can do this with threads, but getting result back and manage lifecycle is pretty tricky without propper abstraction like RxJava or Kotlinx.Coroutines
x
thanks