https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tristan Caron

12/14/2018, 4:54 PM
Hello, About the JS implementation of
kotlinx.coroutines
. What is the base? I suppose
Deferred
is internally using
Promise
, but what about
Job
? Is it working with
Worker
?
g

gildor

12/14/2018, 5:44 PM
Deferred is not based on promises
Same for Job
Coroutines on JS are single threaded, so no workers out of the box
t

Tristan Caron

12/14/2018, 5:53 PM
Thank you, I get it
g

gildor

12/15/2018, 2:49 AM
But there are adapters to convert coroutines to promises or to await Promises
t

Tristan Caron

12/16/2018, 12:22 PM
I just wanted to know if the compiler to js had find a way to run the code in a worker. I guess I could figure out a way to do it with a Gradle plugin. Anyway, I am sure there is way. I'll investigate with modern framework, I know they keep some logic away from the thread handling the DOM. Thank you for your help.
g

gildor

12/16/2018, 1:40 PM
Sure, you can run the code in a worker, like any other JS code. You just should compile some Kotlin code to JS and run it on a worker
You even can use libraries that provide Promise based API for workers so it allow even use coroutines to await for result, but the only problem that you have to compile UI and worker code in separate modules to get 2 separated JS files from 2 Kotlin modules
t

Tristan Caron

12/16/2018, 2:35 PM
Yes, or I'll just see what will happen with WASM and Kotlin/Native 🙂
g

gildor

12/16/2018, 4:10 PM
Wasm? How this related with workers? As I know threads are not available on Wasm yet, so not sure what you mean You can run wasm code on worker, but general approach is not somehow different comparing with Kotlin/JS except than JS backend is much more stable than native (actually the same with JS can wasm for now)
t

Tristan Caron

12/16/2018, 7:16 PM
According to this article http://fitzgeraldnick.com/2018/12/14/rust-and-webassembly-in-2019.html multithreading should available soon. A plugin could help, and I will have to generate multiple files. Considering the fellowing code:
Copy code
val personA = Person()
GlobalScope.launch {
  val personB = Person()
}
Will generate
Copy code
- main_code.js
  - person_class.js
  - worker_code.js
  - kotlin.js
person_class.js
because it is used in the two threads. And if we detect that kind of code
Copy code
val service = Service()
GlobalScope.launch {
    val person = service.getPerson()
}
The plugin should generate the code for the communication between the two process. So maybe it's better to wait for WASM and have built-in solutions 🙂 WebKit team had a proposal https://webkit.org/blog/7846/concurrent-javascript-it-can-work/
3 Views