Reputation: 1416
I have a for loop that consists of looping towards infinity
and inside that for loop, there is a Thread.sleep(T)
function, the sleeping time varies from 50ms to 1s.
I know there are performance and user experience costs for using a sleep function inside a loop.
So what are the Kotlin alternatives ? (I found answers but all of them are in Java, I wanna know the best alternatives in Kotlin)
Upvotes: 1
Views: 3993
Reputation: 174
Use Kotlin Coroutines there is delay(millis:Long) function that is cheaper than Thread.sleep()
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
Upvotes: 2