https://kotlinlang.org logo
Title
o

Osmium

06/15/2021, 6:55 PM
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?
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:
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

louiscad

06/15/2021, 8:49 PM
r

Robert Jaros

06/16/2021, 7:16 AM
In KVision you can use
onClickLaunch()
extension function from
kvision-event-flow
module which is suspending and using internal KVision coroutine scope.