Colton Idle
08/21/2023, 10:44 PMviewModelScope.launch {
while (true) {
delay(5_000)
state.counter++
}
}
it did not hang. so I took a look into delay
and it doesn't specify withContext or anything. Where does that delay actually happen? Am I missing something basic here?jw
08/21/2023, 10:47 PMjw
08/21/2023, 10:47 PMjw
08/21/2023, 10:48 PMJoffrey
08/21/2023, 10:58 PMColton Idle
08/22/2023, 12:32 AMColton Idle
08/22/2023, 12:33 AMColton Idle
08/22/2023, 12:34 AMTolriq
08/22/2023, 5:37 AMxoangon
08/22/2023, 6:50 AMdelay
executed on the main thread, wouldn't freeze the UI. This is because delay
is suspend function and, when suspend functions get effectively suspended, what's really happening is that the function finishes returning COROUTINE_SUSPENDED
and immediately releasing the thread while waiting to resume (you can see this if you take a look into the equivalent Java code).
If you want to block the UI, you should use blocking code. The following code (only working on JVM targets) will freeze the UI:
viewModelScope.launch {
while (true) {
Thread.sleep(5_000)
state.counter++
}
}
Tolriq
08/22/2023, 6:57 AMsuspend fun doHeavyWork() { var i = 0; while(true) { i++ } }
And call that from maindispatcher it will block UI.Tolriq
08/22/2023, 6:59 AM