Reputation: 1042
I'm having the following snippet
verticalLayout {
gravity = Gravity.CENTER
button("BUTTON").onClick {
trace("click on process")
runBlocking {
trace("blocking start") // #1
delay(20000L) #2
trace("blocking end") // #3
}
trace("click process end")
}
}
trace is a function defined as a utility function to log out messages using Log.e with current thread name
when i click the button, all code run as expected and logs show all trace functions are called in main thread log for #3 appears after #1 within 20000L ms and no ANR Dialog shows
but strange things happened, during the 20000L ms, the button hold the pressed state even when i release the button right after click, then i realized the pressed state is restored when onClick method ends,
i had a raw concept that coroutine is a compiler magic using CPS to transform the code into a callback style function like follow
delay(20000L,callback = { trace("blocking end ")})
so i have the following questions
Upvotes: 3
Views: 1909
Reputation: 28648
You are using runBlocking
which is named that way because it blocks the thread it is invoked on for the duration of coroutine execution. In your particular case, you are blocking your UI thread with runBlocking
.
You can replace runBlocking
with launch(UI)
to start a background coroutine on UI thread without blocking UI thread. You can learn more about various ways to work with coroutines in the Guide to kotlinx.coroutines and in the Guide to UI programming with coroutines.
Upvotes: 4