https://kotlinlang.org logo
Title
n

Natsuki(开元米粉实力代购)

06/16/2017, 7:27 AM
verticalLayout {
            button("Delay").onClick {
                log("click begin")
                runBlocking {
                    log("delay begin")
//                    delay(30000L)  
                    Thread.sleep(30000L)
                    log("delay end")
                }
                log("click end")
            }
        }
guys,i’m a newbee in coroutine, i tried these piece of code, when change delay to sleep, an ANR was issued by system i want to know why delay does not issue an ANR and what is main thread doing when the delay clause is executing, would anyone be kind enough to explain this for me ?
u

uli

06/16/2017, 7:49 AM
natsuki:
delay
is a suspending function. The compiler will generate a continuation for you, that is then posted to the main thread. Simplified it will produce something like
log("delay begin")
postDelayed(30000L) {  
    log("delay end")
}
In the real world, state machines are used for efficient implementation: https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#state-machines
n

Natsuki(开元米粉实力代购)

06/16/2017, 7:53 AM
that is the part where I’m confusing the explanation above require the framework should have an handler-alike mechanism, which should not be the case, and in log function i’m dumping the stacktrace, and confirm that no
postDelay
or related mechanism is used ,i.e the log(“delay end”) method with stacktrace from onclick !! not handleMessge which should be if postDelay (or related) is used
is this part (what i am confusing ) implemented by state-machine ? i’ll deep into the document right now
u

uli

06/16/2017, 8:14 AM
well, runBlocking will actually start it's own runloop on the current thread, if required. this is actually the 'blocking' in 'runBlocking'. Then it will schedule the continuation to run on that run loop, waiting via UNSAFE.park() which is kind of like Thread.wait() until the continuation is ready to run. So I agree, runBlocking should block your UIThread (as the name suggests), giving you an ANR
anyway, adapting @groostav answer to android you would do a launch(UI), with UI being:
kotlinx.coroutines.experimental.android.UI
This provides the postDelayed mechanism of scheduling the continuation back to the UIThread, avoiding all locking