钵钵鸡实力代购
钵钵鸡实力代购

Reputation: 1042

kotlin coroutine and main handler relationship

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

  1. in the end who and when actually calls callback(e.g trace("blocking end")) if the answer is the main looper or something (for nodejs ,maybe the eventloop), does we should adapt the framework for coroutine and let coroutine put event to the queue ?
  2. saying that coroutine is actually compiler magic, can we write the same code as the snippet above which does not trigger an ANR but keep pressed state for 20000L ?

Upvotes: 3

Views: 1909

Answers (1)

Roman  Elizarov
Roman Elizarov

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

Related Questions