Is there a wait function in kotlin? (I don't mean a Timer Schedule, but actually pause the execution). I have read that you can use Thread.sleep()
. However, it doesn't work for me, because the function can't be found.
There is no direct way to achieve this in Kotlin, but we can use Java library functions in Kotlin for this purpose since Kotlin is based on Java. We will use the Timer() and schedule() functions to call a function after a delay.
Kotlin does not have the wait() function, but it has the sleep() function. The Kotlin sleep() function suspends the execution of a particular coroutine. While this does not pause the execution, it allows the execution of other coroutines.
Thread sleep always takes a time how long to wait: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)
public static void sleep(long millis) throws InterruptedException
e.g.
Thread.sleep(1_000) // wait for 1 second
If you want to wait for some other Thread to wake you, maybe `Object#wait()' would be better
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
public final void wait() throws InterruptedException
Then another thread has to call yourObject#notifyAll()
e.g. Thread1 and Thread2 shares an Object o = new Object()
Thread1: o.wait() // sleeps until interrupted or notified Thread2: o.notifyAll() // wake up ALL waiting Threads of object o
Please try this, it will work for Android:
Handler(Looper.getMainLooper()).postDelayed( { // This method will be executed once the timer is over }, 1000 // value in milliseconds )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With