Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Wait function

Tags:

kotlin

wait

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.

like image 338
OhMad Avatar asked Jul 20 '17 11:07

OhMad


People also ask

How do you delay a function in Kotlin?

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.

How do I add a wait on Kotlin?

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.


2 Answers

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 
like image 191
guenhter Avatar answered Sep 17 '22 18:09

guenhter


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 ) 
like image 28
Aditay Kaushal Avatar answered Sep 17 '22 18:09

Aditay Kaushal