Use kotlinx.coroutines.delay(...) inside a coroutine instead of Thread.sleep(...).
Thread.sleep blocks the current thread. delay suspends the coroutine without blocking the thread, so other coroutines can keep running.
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
println("Before delay")
delay(1_000) // suspends for 1 second, does not block the thread
println("After delay")
}
If you currently have:
Thread.sleep(1000)
replace it with:
delay(1000)
But note: delay is a suspend function, so it can only be called from another suspend function or from inside a coroutine builder such as launch, async, or runBlocking.
Example with launch:
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch {
delay(1000)
println("Coroutine finished after 1 second")
}
println("This prints immediately")
}
Example in a suspend function:
import kotlinx.coroutines.delay
suspend fun doWork() {
delay(500)
println("Work done")
}
Avoid doing this in coroutines:
Thread.sleep(1000) // blocks the underlying thread
Prefer:
delay(1000) // suspends only the coroutine
