Hi! I'm trying to understand how to use coroutines in a non-coroutines JS frameworks without using GlobalScope a lot.
Today I tried to rewrite application using one GlobalScope and nested
launch
methods so coroutine hierarchy will be structured.
But. How to deal with callbacks?
Copy code
fun main() {
GlobalScope.launch {
launch {
root("main") { div("Hello KVision!") }
}
launch {
root("extras") {
button {...}.onClick {
this@launch.launch {
ktorClient.get("/api/users/current") {...} // will not be called
}
}
}
}
}
}
Should I use GlobalScope in case of event listeners like onClick and so on?
l
louiscad
06/15/2021, 7:37 PM
You can turn click listeners into suspending functions with
suspendCancellableCoroutine
. Name example:
awaitOneClick()
o
Osmium
06/15/2021, 8:35 PM
@louiscad Readed about suspendCancellableCoroutine. No, it's not the case. I solved it with next piece of code:
Copy code
fun setup(parentScope: CoroutineScope) {
val job = Job()
val scope = CoroutineScope(job)
button {}.onClick {
scope.launch { job.complete() }
}
scope.launch { job.join() }
}