Hi! I'm trying to understand how to use coroutines...
# coroutines
o
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
You can turn click listeners into suspending functions with
suspendCancellableCoroutine
. Name example:
awaitOneClick()
o
@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() }
}
But thank you for pointing me in that direction!
l
r
In KVision you can use
onClickLaunch()
extension function from
kvision-event-flow
module which is suspending and using internal KVision coroutine scope.