How to call a function after delay in Kotlin?

前端 未结 11 1897
南笙
南笙 2020-11-30 19:07

As the title, is there any way to call a function after delay (1 second for example) in Kotlin?

相关标签:
11条回答
  • 2020-11-30 19:55

    There is also an option to use Handler -> postDelayed

     Handler().postDelayed({
                        //doSomethingHere()
                    }, 1000)
    
    0 讨论(0)
  • 2020-11-30 19:57

    Many Ways

    1. Using Handler class

    Handler().postDelayed({
        TODO("Do something")
        }, 2000)
    

    2. Using Timer class

    Timer().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")
    }
    

    3. Using Executors class

    Executors.newSingleThreadScheduledExecutor().schedule({
        TODO("Do something")
    }, 2, TimeUnit.SECONDS)
    
    0 讨论(0)
  • 2020-11-30 19:58

    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()
    }
    
    0 讨论(0)
  • 2020-11-30 20:02

    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()
    }
    
    0 讨论(0)
  • 2020-11-30 20:03
    val timer = Timer()
    timer.schedule(timerTask { nextScreen() }, 3000)
    
    0 讨论(0)
提交回复
热议问题