What is the best practice to use Coroutines (my us...
# coroutines
s
What is the best practice to use Coroutines (my use case is Fetch API +
await()
on the returned
Promise
) in JavaScript callbacks like
onclient =  { }
? cc @Vsevolod Tolstopyatov [JB]
đź‘€ 1
Should I create some kind of
EventTarget.addSuspendingEventListener
extension with a suspending lamda? Do you plan to generate Coroutines friendly lambda at some point?
z
I’m not too familiar with the JS Fetch API, but in general: - If you have a single-fire callback you can turn it into a suspend function. - If you have a multi-fire callback you can turn it into a
Flow
.
âž• 1
g
The easiest solution is just launch a coroutine using launch from this callback. But more idiomatic and powerful is as Zach write, write an adapter for this particular callback
v
It depends on what you want, but in general, it’s pretty similar to what you can do with callbacks on JVM (modulo missing runBlocking that can be workarounded by launching coroutine). Single-shot callbacks can be represented as suspend functions (via
suspendCancellableCoroutine
), channel and flow, whatever suits you. For multishot,
callbackFlow
is probably the best option. Issues with missing JS integrations are welcome 🙂
s
Thanks for your feedback, that what I have done, but I was wondering if Kotlin/JS could provide Coroutines friendly callbacks by default and more generally more idiomatic Kotlin APIs out of the box.
Since it is automatically generated
(I think)
I just want to discuss the idea
v
it would be nice if Kotlin/JS could interop with JS async (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function), if that’s what you mean. But AFAIK K/JS team doesn’t have this in plans
s
Ok I will have a deeper look
v
JS is a bit trickier than JVM because we cannot block on the K <-> JS boundary, so basically there is two options: interop with JS async somehow (and maybe we can do it without compiler support) or launch a promise/coroutine and “suspend” there to mimic regular JS “promise-like” API