delay suspends the coroutine and supports coroutine cancellation. Thread.sleep blocks the current thread, including Main if called there. Moving sleep inside launch does not change its blocking behavior.
For a cancellable UI countdown, use a suspending wait:
val countdown = scope.launch {
for (remaining in 3 downTo 1) {
showRemaining(remaining)
delay(1_000)
}
onFinished()
}
// If the countdown is no longer wanted:
countdown.cancel()
Here scope must have an appropriate owner. The callbacks are application-specific. This is a simple countdown, not a precise clock: scheduler delays can accumulate. For time-sensitive display, calculate remaining time from a monotonic deadline.
Replacing Thread.sleep(1000) with delay(1000) does not fix a test that guesses when loading finishes. Await the actual completion signal or advance a coroutine test scheduler. An arbitrary wait can remain flaky even though it no longer blocks.
Does cancelling a coroutine interrupt every blocking Java call? No. Cancellation is cooperative; integrations may require a cancellation hook or an interruptible adapter where the API supports interruption.
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐