Pick the fix
This function is called from the main thread and the UI freezes. What is the right fix?
suspend fun countPrimes(limit: Int): Int {
var count = 0
for (n in 2..limit) {
if ((2..Math.sqrt(n.toDouble()).toInt()).none { n % it == 0 }) count++
}
return count
}Hint 1 of 2
Which thread is the loop running on?
Hint 2 of 2
Who should decide the dispatcher: the caller or the function?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Wrap the body in withContext(Dispatchers.Default) { ... }
Correct. The function becomes main-safe: it moves its own CPU work off the main thread.
Why not the others?
- B Nothing;
suspendalready runs it in the background. suspend doesn't change threads. The loop runs on the caller's main thread. - C Add
delay(1)at the start. That suspends once, then resumes on main and runs the loop there anyway. - D Call it with
GlobalScope.async. That leaks the work outside any lifecycle and doesn't fix the function itself.