Predict the output
This runs on the Android main thread. What happens?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val name = runBlocking {
withContext(Dispatchers.Main) { "ready" }
}
title = name
}Hint 1 of 2
Which thread does runBlocking block?
Hint 2 of 2
Where does withContext(Main) need to run?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A It deadlocks: the main thread waits for work that needs the main thread
Correct. withContext(Main) has to post to the main thread, which is blocked inside runBlocking.
Why not the others?
- B It sets the title to ready right away. The main thread is blocked, so the posted block never runs.
- C It crashes with NetworkOnMainThreadException. There's no network call here.
- D It sets the title after one frame. The frame never comes because the main thread is stuck.
Illustrative, based on Compose and Android rules; not a device recording
Text version
| Frame | Work (ms) | Result |
|---|---|---|
| F1 | 6 | on time |
| F2 | 8 | on time |
| F3 | 7 | on time |
| F4 | 9 | on time |
| F5 | 6 | on time |
| F6 | 8 | on time |
0 dropped frames at 60 Hz (16.7 ms budget); ANR dialog at 5 s: no.
| Frame | Work (ms) | Result |
|---|---|---|
| F1 | 8 | on time |
| F2 | 5000 | ⏱ late (the next 299 dropped) |
| F3 | – | ✕ dropped (F2 still running) |
| F4 | – | ✕ dropped (F2 still running) |
| F5 | – | ✕ dropped (F2 still running) |
| F6 | – | ✕ dropped (F2 still running) |
| F7–F301 | – | ✕ dropped ×295 (F2 still running) |
299 dropped frames at 60 Hz (16.7 ms budget); main thread blocked for 5 s; ANR dialog at 5 s: yes.