https://kotlinlang.org logo
Title
a

andrewreitz

02/09/2021, 7:30 PM
If I have a suspend function that I want to call on a button click event what's the best way to do that? Example
Button(
   onClick = { runit() }
) {
  Text("Run")
}
Where runit is the suspend function. I can put it in a runBlocking, but that locks up the whole UI and seems incorrect in this situation.
j

jim

02/09/2021, 8:02 PM
I suppose it depends why
runit()
is a suspending function, but yeah, if it's a potentially slow function, you should probably
launch
it into a new thread or coroutine scope. https://kotlinlang.org/docs/reference/coroutines/basics.html
a

andrewreitz

02/09/2021, 9:24 PM
What scope would launch come off of?
fun main = Window() { }
Is there a scope build for the window already?
j

jim

02/09/2021, 9:30 PM
Depends on what you're trying to do. Typically, for most actions, I'd imagine you'd want an application scope or to use
GlobalScope
since you typically don't want the action to suddenly die if the user switches tabs or the widget is otherwise removed from the hierarchy.
👍 1
a

andrewreitz

02/10/2021, 2:55 PM
runBlocking
just uses global scope right? So I could maybe do
runBlocking { Window() { ... } }
then I should be able to use launch and async inside the window block? Seems like it might be nice if window had a context even if it was just global.