https://kotlinlang.org logo
Title
s

sdeleuze

10/28/2019, 1:51 PM
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

Zach Klippenstein (he/him) [MOD]

10/28/2019, 9:10 PM
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

gildor

10/29/2019, 3:20 AM
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

Vsevolod Tolstopyatov [JB]

10/29/2019, 9:54 AM
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

sdeleuze

10/29/2019, 9:55 AM
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

Vsevolod Tolstopyatov [JB]

10/29/2019, 9:58 AM
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

sdeleuze

10/29/2019, 10:00 AM
Ok I will have a deeper look
v

Vsevolod Tolstopyatov [JB]

10/29/2019, 10:01 AM
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