7

I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

println("hello")
// a 2 seconds delay
println("world")
Zain
  • 37,492
  • 7
  • 60
  • 84
tonga
  • 191
  • 3
  • 12

4 Answers4

14

It's simple. Just use a coroutine. Like this:

fun main() = runBlocking { 
    launch { 
        delay(2000L)
        println("World!") 
    }
    println("Hello")
}

Don't forget to import kotlin coroutine like this:

import kotlinx.coroutines.*

Happy coding in kotlin!!!

Syed Faizan Ali
  • 361
  • 1
  • 8
  • Why would you want to run this blocking? What would happen if the delay is bigger and in the meantime you exit the app? – David Jan 25 '23 at 20:15
5

there are some ways:

1- use Handler(base on mili-second)(Deprecated):

println("hello")
Handler().postDelayed({
   println("world")
}, 2000)

2- by using Executors(base on second):

println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)

3- by using Timer(base on mili-second):

println("hello")
Timer().schedule(2000) {
  println("world")
}
soheil ghanbari
  • 388
  • 1
  • 7
0

Use:

viewmodelScope.launch {
    println("hello")
    delay(2000)
    println("world")
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
mikelantzelo
  • 182
  • 1
  • 9
  • If the apps goes to the background while your delay is running println("world") will run anyways, is that what you want? – David Jan 25 '23 at 20:17
-1

If you don't want to use any dependencies then you can use Thread.sleep(2000L) Here, 1 second = 1000L The code should look like this,

println("hello")
Thread.sleep(2000L)
println("world")
nym
  • 9
  • 1