作为标题,在Kotlin中是否有方法在延迟(例如1秒)后调用函数?


当前回答

还有一个选项使用Handler -> postDelayed

 Handler().postDelayed({
                    //doSomethingHere()
                }, 1000)

其他回答

你可以使用日程安排

inline fun Timer.schedule(
    delay: Long, 
    crossinline action: TimerTask.() -> Unit
): TimerTask (source)

例子(谢谢@Nguyen Minh Binh -在这里找到它: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()
}

如果你正在使用最新的Android api, Handler空构造函数已经被弃用,你应该包括一个循环程序。你可以很容易地通过loop . getmainlooper()得到一个。

    Handler(Looper.getMainLooper()).postDelayed({
        //Your code
    }, 2000) //millis

我建议使用kotlin协程,如果你想取消它。它结构简单,重量轻。

fun repeatFun(): Job {
    return coroutineScope.launch {  
        while(isActive) {
            //do your work here
            delay(1000)
        }
    }
}

//start the loop
val repeatFun = repeatRequest()

//Cancel the loop
repeatFun.cancel()

如果你在一个带有viewModel作用域的片段中,你可以使用Kotlin协程:

    myViewModel.viewModelScope.launch {
        delay(2000)
        // DoSomething()
    }

还有一个选项使用Handler -> postDelayed

 Handler().postDelayed({
                    //doSomethingHere()
                }, 1000)