Kotlin - Standby Function

Is there a wait function in kotlin? (I do not mean the timer schedule, but actually pause execution). I read what you can use Thread.sleep(). However, this does not work for me, because the function cannot be found.

+25
source share
5 answers

Sleep snow always takes a long time to wait: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)

public static void sleep(long millis)
                  throws InterruptedException

eg

Thread.sleep(1_000)  // wait for 1 second

If you want to wait until some other thread wakes you up, perhaps "Object # wait ()" will be better

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait ()

public final void wait()
                throws InterruptedException

Then another thread should call yourObject#notifyAll()

, Thread1 Thread2 Object o = new Object()

Thread1: o.wait()      // sleeps until interrupted
Thread2: o.notifyAll() // wake up ALL waiting Threads of object o
+22

, Android:

Handler().postDelayed(
    {
        // This method will be executed once the timer is over
    },
    1000 // value in milliseconds
)
+15

Kotlin 1.1, delay :

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

Kotlin 1.2 kotlinx.coroutines.experimental. .

UPD: Kotlin 1.3 , kotlinx.coroutines, .

UPD 2: , , , runBlocking {}:

runBlocking {
    delay(2, TimeUnit.SECONDS)
}
+10

JDK.

The previous answer gives Thread.sleep(millis: Long). Personally, I prefer the TimeUnit class (starting with Java 1.5), which provides a more complete syntax.

TimeUnit.SECONDS.sleep(1L)
TimeUnit.MILLISECONDS.sleep(1000L)
TimeUnit.MICROSECONDS.sleep(1000000L)

They use Thread.sleepbehind the scenes, and they can also have Thread.sleepInterruptedException.

+10
source

You can easily achieve this 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 (application)

dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
}
+3
source

Source: https://habr.com/ru/post/1681868/


All Articles