Kotlin - Wait function
Asked Answered
E

9

108

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.

Epistaxis answered 20/7, 2017 at 11:42 Comment(1)
Sleep is always available, because it is part of the standard JDK. You just didn't call it with the appropriate parameters.Lucilucia
L
99

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
Lucilucia answered 20/7, 2017 at 11:44 Comment(1)
Or just use notify if there is only one other thread that can lock the same object.Exsiccate
M
70

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
)
Matronly answered 20/7, 2017 at 11:45 Comment(4)
Deprecated — use: Handler(Looper.getMainLooper()).postDelayed({ // Your Code }, 1000)Howlett
This should be the accepted answer imo. Unless the original question was to hang the entire Thread, though "pausing execution" and sleeping threads are usually expressed similarly when explaining, in reality are not what the user needs.Rosenberger
@MariosYiannakou No, This answer is specific to Android but OP is asking generally how to wait in Kotlin.Reactivate
The question is not tagged with "android", so why assume that android is the platform?Likeminded
E
41

Since new coroutines feature became available in Kotlin version 1.1 you can use non-blocking delay function with such signature:

suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS)

In Kotlin 1.2 it is still located in kotlinx.coroutines.experimental package. Experimental status of coroutines is described here.

UPD: Kotlin 1.3 was released, coroutines were moved to kotlinx.coroutines package, they are no longer experimental feature.

UPD 2: To use this method inside non-suspendable methods it's possible to make it blocking, like any other suspendable methods, by surrounding with runBlocking {}:

runBlocking {
    delay(2, TimeUnit.SECONDS)
}
Exterminatory answered 3/2, 2018 at 17:52 Comment(1)
delay no longer takes a TimeUnit parameter.Haase
B
28

You can achieve this easily with Kotlin coroutines

class SplashActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        CoroutineScope(Dispatchers.IO).launch {
            delay(TimeUnit.SECONDS.toMillis(3))
            withContext(Dispatchers.Main) {
                Log.i("TAG", "this will be called after 3 seconds")
                finish()
            }
        }
        Log.i("TAG", "this will be called immediately")
    }
}

build.gradle(app)

dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
}
Bluebell answered 11/2, 2019 at 8:46 Comment(1)
not only best written - it complies with google demands of using coroutines instead of handlers and threads on our own!Hombre
D
25

You can use stuff of the standard JDK.

Another response suggests Thread.sleep(millis: Long). Personally I prefer the TimeUnit class (since Java 1.5) which provides a more comprehensive syntax.

TimeUnit.SECONDS.sleep(1L)
TimeUnit.MICROSECONDS.sleep(1000_000L)

They use Thread.sleep behind the scene, and they can throw InterruptedException too. Unfortunately, as pointed by @AndroidDev in a comment, they do not cooperate with Kotlin coroutines (since Kotlin 1.1). So we should prefer delay function in this context.

public suspend fun delay(timeMillis: Long): Unit
public suspend fun delay(duration: Duration): Unit
Distillery answered 7/8, 2018 at 9:36 Comment(1)
Don't use anything that uses sleep (such as Thread.sleep) inside a coroutine (suspend function). Kotlin will complain about it with "inappropriate thread-blocking method call'.Haase
F
5

you can use to wait or sleep for 2 seconds

TimeUnit.SECONDS.sleep(2L)
TimeUnit.SECONDS.sleep((seconds you want to sleep) + L)
Fulton answered 19/1, 2022 at 16:36 Comment(0)
P
0

We can achieve functionality using Mutex class in kotlin. '.lock()' and '.unlock()' are the methods were similar to wait and notify in java.

Particularism answered 14/8, 2023 at 12:40 Comment(0)
J
0

According to kotlin docs: wait()/notify(), you can simply convert an Any into an Object if you really want to rely on the native mechanism:

// The `Any` aka. `Object` in Java accessed by multiple threads.
val sharedList: List<Any> = ArrayList()

... ...

// One thread accessing the `Any`
synchronized(sharedList) {
    while(needWait) {
        try {
            // Convert it to `Object` and wait, thus release the lock.
            (sharedList as java.lang.Object).wait()
        } catch(_: InterruptedException) {}
    }
}

You can also wrap it as an extended function:

private fun Any.wait() = (this as java.lang.Object).wait()
private fun Any.notify() = (this as java.lang.Object).notify()

// Then you can use it as what you do in Java
synchronized(lock) {
    try {
        lock.wait()        // extended function
    } catch(_: InterruptedException) {}
}
Jhansi answered 14/2, 2024 at 14:58 Comment(0)
C
-1

You can use

SystemClock.sleep(1000)
Collagen answered 28/10, 2019 at 5:47 Comment(2)
That's an Android thingLounging
SystemClock.sleep() doesn't throw InterruptedException; Thread.interrupt(), better than using Thread.sleep()Maurene

© 2022 - 2025 — McMap. All rights reserved.