Kotlin - Wait function

KotlinWait

Kotlin Problem Overview


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.

Kotlin Solutions


Solution 1 - Kotlin

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

Solution 2 - Kotlin

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
)

Solution 3 - Kotlin

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)
}

Solution 4 - Kotlin

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

Solution 5 - Kotlin

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'
}

Solution 6 - Kotlin

you can use to wait or sleep for 2 seconds

TimeUnit.SECONDS.sleep(2L)

*

TimeUnit.SECONDS.sleep((seconds you want to sleep) + L)

Solution 7 - Kotlin

You can use

SystemClock.sleep(1000)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOhMadView Question on Stackoverflow
Solution 1 - KotlinguenhterView Answer on Stackoverflow
Solution 2 - KotlinAditay KaushalView Answer on Stackoverflow
Solution 3 - KotlinN. KudryavtsevView Answer on Stackoverflow
Solution 4 - KotlinmcooliveView Answer on Stackoverflow
Solution 5 - KotlinmurgupluogluView Answer on Stackoverflow
Solution 6 - Kotlinfarzannezarat1View Answer on Stackoverflow
Solution 7 - KotlinLeonid IvankinView Answer on Stackoverflow