As the title, is there any way to call a function after delay (1 second for example) in Kotlin
?
There is also an option to use Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)
Handler
classHandler().postDelayed({
TODO("Do something")
}, 2000)
Timer
classTimer().schedule(object : TimerTask() {
override fun run() {
TODO("Do something")
}
}, 2000)
Shorter
Timer().schedule(timerTask {
TODO("Do something")
}, 2000)
Shortest
Timer().schedule(2000) {
TODO("Do something")
}
Executors
classExecutors.newSingleThreadScheduledExecutor().schedule({
TODO("Do something")
}, 2, TimeUnit.SECONDS)
A simple example to show a toast after 3 seconds :
fun onBtnClick() {
val handler = Handler()
handler.postDelayed({ showToast() }, 3000)
}
fun showToast(){
Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}
You can use Schedule
inline fun Timer.schedule(
delay: Long,
crossinline action: TimerTask.() -> Unit
): TimerTask (source)
example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)
import java.util.Timer
import kotlin.concurrent.schedule
Timer("SettingUp", false).schedule(500) {
doSomething()
}
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)